Search code examples
javascriptarrayssorting

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.


Solution

  • 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())