Move item in array to last position

后端 未结 5 1574
终归单人心
终归单人心 2021-02-02 08:11

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:

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 08:40

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

提交回复
热议问题