Move item in array to last position

后端 未结 5 1583
终归单人心
终归单人心 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:46

    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"));
    

提交回复
热议问题