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

83
我有一个对象数组。我想把选定的对象移到数组的最后位置。我该如何在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"值的对象,然后是有值的对象。

2
一个对象不是一个数组,位置是没有意义的,只有键和值。阅读更多 - https://dev59.com/jW035IYBdhLWcg3wQtsg - vsync
谁说sortedProductRow是一个对象?你也可以使用for in循环遍历数组(虽然我不认为这是个好主意,但是确实可行)。 - Ferdi265
1
嗯,好的,那我不确定我需要做什么。我可以使用for循环遍历这个数组,对象按照它们在“数组”(或对象)中出现的顺序出现。那么如果我想改变它们从for循环中出来的顺序,我需要做什么? - Johan Dahl
8个回答

153

要将数组中指定索引的元素移动到末尾,可以执行以下操作:

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]

注意:

这仅适用于数组(使用[ ... ]语法或Array()创建),而不是对象(使用{ ... }语法或Object()创建)。


3
需要进一步解释。尽管这解决了问题,但没有人学到任何东西。 - Devashish
1
嗨@Ferdi265,你能解释一下为什么在array.splice方法后面加上[0]吗?先谢谢了。 - vandu
6
Array.splice()返回一个包含所有删除元素的数组,因此在这种情况下,它返回[6]。我们只想将6推到数组的末尾,所以我们取该数组的第一个元素。如果您不添加[0],则会得到[1, 2, 3, 4, 5, [6]] - Ferdi265
移动一个元素到指定的索引位置,我们可以这样做: arr.splice(index, 0, arr.splice(arr.indexOf(6), 1)[0]); - HDKT
也许我们还可以做类似这样的事情:Array.prototype.move = function(element, index) { arr.splice(index, 0, arr.splice(arr.indexOf(element), 1)[0]); } - HDKT
@HDKT在2020年及以后吗?不需要。你需要有一个非常好的理由去修改Array.prototype - targumon

18

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

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

优雅的解决方案,但这只能将数组的第一个元素移动到末尾。 - Ferdi265
谢谢,但我不想移动第一个元素。我正在循环遍历sortedProductRow数组/对象,并且当我找到一个属性名为“parent_product_type”的具有值的属性时,我想将其移动到数组的最后位置。这样,我的数组将首先包含没有“parent_product_type”属性值的对象,然后是所有具有此属性值的对象。 - Johan Dahl
1
@JohanDahl 抱歉 :) 我更新了答案,使其更有用 :) 所以试一下吧。 - hex494D49
谢谢您的回答!最终我使用了Ferdi的第二种方法,效果很好。 - Johan Dahl
1
对于那些想要返回被移动到数组末尾的元素的人:const output = a[a.push(a.shift())-1]; - JacobF
显示剩余2条评论

11

不可变方式:

const changedArr = [...prevArr.filter(a => a !== element), element]

9

这样更简洁,不使用数组索引[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"]

5
使用匿名函数,您可以传入要筛选的数组和值。
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');

您可以进一步缩短这个内容:
let concatToEnd = (arr,val) => arr.filter(x => x !== val).concat(arr.filter(x => x === val))

该函数过滤掉与传入的值不相等的项,然后将另一个过滤函数的结果(过滤掉与传入值相等的项)连接到已过滤数组的末尾。
该函数本质上将数组分为两个过滤后的部分,然后再将它们连接在一起。
此功能未经过您的用例测试,但我使用类似的方法将数组中的所有数字移动到索引的末尾。

1
将任何元素移动到最后一个位置 - 适用于 lodash 用户:
    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

0

您可以通过拼接它们,然后将它们展开推送中来移动任意数量的项目。

const numberOfItems = 3;
let items = [1,2,3,4,5,6,7,8,9];
items.push(...items.splice(0, itemsToMove))

0

将所有相等的项目移动到末尾也可以通过连接来完成。

const myArray = [1, 0, 3, 5, 0, 'a', 3, 's']
    
const moveZerosToEnd = (arr) => {
   return arr.filter(item => item !== 0).concat(arr.filter(item => item === 0))
}

console.log(myArray)                 // [1, 0, 3, 5, 0, 'a', 3, 's']
console.log(moveZerosToEnd(myArray)) // [1, 3, 5, 'a', 3, 's', 0, 0] 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接