将数组中的项目移动到最后一个位置

新手上路,请多包涵

我有一组对象。我想将选定的对象移动到数组中的最后一个位置。我如何在 javascript 或 jquery 中执行此操作?

这是我的一些代码:

 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
}

我用 for 循环遍历它,我希望对输出进行排序,以便所有不具有“parent_product_type”值的对象首先出现,然后是具有值的对象。

原文由 Johan Dahl 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

要将一个元素(您知道其索引)移动到数组的末尾,请执行以下操作:

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

如果您没有索引,只有元素,请执行以下操作:

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

例子:

     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]

笔记:

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

原文由 Ferdi265 发布,翻译遵循 CC BY-SA 3.0 许可协议

将数组 的第一个元素 移动到同一个数组 的末尾

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

或者这样

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

将数组的 任意元素 移动到同一数组中的 任意位置

     // 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]

或者它也可以转换为原型,就像这样 x 代表元素的当前位置,而 y 代表数组中的新位置

 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"]

对@jkalandarov 评论的回答

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

原文由 hex494D49 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题