Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move item in array to last position

I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?

Here is some code I have:

var sortedProductRow = this.product_row;

for (var s in sortedProductRow) {
    if (sortedProductRow[s]["parent_product_type"] != "")
        // Move this object to last position in the array
}

I'm looping through this with a for loop, and I want the output to be ordered so that all objects that does not have a "parent_product_type" value comes first, then those with a value.

like image 696
Johan Dahl Avatar asked Jul 23 '14 11:07

Johan Dahl


People also ask

How do you change the position of an item in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you move specified number of elements to the end of an array in JavaScript?

Run a for loop from index i = 0 till X-1. In each iteration take the element at current index and append it at the end of the array. After the iteration is complete, use the JavaScript splice() method to remove first X elements from the array to get the resultant array.

How do you move the last element of an array first?

Now, if you need to move the last item to the first position, just use the return function array. pop() as input to the function array. unshift().

How do you target the last element of an array?

To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>. length - 1 item.


6 Answers

to move an element (of which you know the index) to the end of an array, do this:

array.push(array.splice(index, 1)[0]);

If you don't have the index, and only the element, then do this:

array.push(array.splice(array.indexOf(element), 1)[0]);

Example:

    var arr = [1, 2, 6, 3, 4, 5];
    arr.push(arr.splice(arr.indexOf(6), 1)[0]);
    console.log(arr); // [1, 2, 3, 4, 5, 6]

NOTE:

this only works with Arrays (created with the [ ... ] syntax or Array()) not with Objects (created with the { ... } syntax or Object())

like image 100
Ferdi265 Avatar answered Sep 30 '22 01:09

Ferdi265


Moving the first element of an array to the end of the same array

    var a = [5,1,2,3,4];
    a.push(a.shift());
    console.log(a); // [1,2,3,4,5]

or this way

    var a = [5,1,2,3,4];
    var b = a.shift();
    a[a.length] = b;
    console.log(a); // [1,2,3,4,5]

Moving any element of an array to any position in the same array

    // move element '5' (index = 2) to the end (index = 4)
    var a = [1, 2, 5, 4, 3];
    a.splice(4,0,a.splice(2,1)[0]);
    console.log(a); // [1, 2, 4, 3, 5]

or it could be converted to a prototype as well, like this where x represents the current position of element while y represents the new position in array

var a = [1, 2, 5, 4, 3];
Array.prototype.move = function(x, y){
      this.splice(y, 0, this.splice(x, 1)[0]);
      return this;
    };
    
    a.move(2,4);
    console.log(a); // ["1", "2", "4", "3", "5"]

Answer to the @jkalandarov comment

function moveToTheEnd(arr, word){
  arr.map((elem, index) => {
    if(elem.toLowerCase() === word.toLowerCase()){
      arr.splice(index, 1);
      arr.push(elem);
    }
  })
  return arr;
}
console.log(moveToTheEnd(["Banana", "Orange", "Apple", "Mango", "Lemon"],"Orange"));
like image 28
hex494D49 Avatar answered Sep 26 '22 01:09

hex494D49


This is more clean, without using the array index of [0]

const colors = ['white', 'black', 'red', 'blue', 'green'];

// will push the blue to the end of the array
colors.push(colors.splice(colors.indexOf('blue'), 1).pop());

console.debug(colors);
// ["white", "black", "red", "green", "blue"]
like image 27
Medo Avatar answered Sep 26 '22 01:09

Medo


Using an anonymous function you can pass in the array and the value to filter by.

let concatToEnd = function (arr, val) {
        return arr.filter(function(x) {
            return x !== val; // filter items not equal to value
        }).concat(arr.filter(function(x) { // concatonate to filtered array
            return x === val; // filter items equal to value 
        })
    );
}

// invoke
concatToEnd(array, 'parent_product_type');

You could probably shorten this further:

let concatToEnd = (arr,val) => arr.filter(x => x !== val).concat(arr.filter(x => x === val))

This function filters the items which do not equal the value passed in, then concatenates the result (to the end of the filtered array) of another filter function which filters out the items which do equal the value you've passed in.

This function essentially separates the array into 2 filtered parts and then concatenates them back together

This hasn't been tested for your use-case, but I've used something similar to move all numbers of an array to the end of the index.

like image 45
UncaughtTypeError Avatar answered Sep 27 '22 01:09

UncaughtTypeError


Immutable way:

const changedArr = [...prevArr.filter(a => a !== element), element]
like image 29
Nagibaba Avatar answered Sep 28 '22 01:09

Nagibaba


Move any element to last position - for lodash users:

    const array = ['A', 'B', 'C', 'D'] // output: A, B, C, D

// finds index of value 'B' and removes it
    _.pull(array , 'B') // output: A, C, D

// adds value of 'B' to last position
    _.concat(array , 'B') // output: A, C, D, B
like image 32
Advem Avatar answered Sep 27 '22 01:09

Advem