【问题标题】:Move item in array to last position将数组中的项目移动到最后一个位置
【发布时间】:2014-07-23 11:33:42
【问题描述】:

我有一个对象数组。我想将选定的对象移动到数组中的最后一个位置。如何在 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”值的对象首先出现,然后是具有值的对象。

【问题讨论】:

  • 一个 object 不是一个 array 并且位置是无意义的,它只是键和值。阅读更多 - stackoverflow.com/q/5525795/104380
  • 谁说sortedProductRow 是一个对象?你也可以用 for in 迭代一个数组(我不是说这是一个好主意,但它是可能的)
  • 嗯,好吧,那我不确定我需要做什么。我可以用 for 循环遍历这个数组,对象按照它们出现在“数组”(或对象)中的顺序出现。那么,如果我想更改它们从 for 循环中出来的顺序,我需要做什么呢?

标签: javascript arrays sorting


【解决方案1】:

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

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

【讨论】:

  • 需要更多解释。虽然这解决了问题,但没有人学到任何东西。
  • 嗨@Ferdi265你能解释一下为什么你在array.splice方法之后添加了[0]。提前致谢
  • Array.splice() 返回一个包含所有已删除元素的数组,因此在本例中为[6]。我们只想将6 推到数组的末尾,所以我们取该数组的第一个元素。如果不添加[0],则会得到[1, 2, 3, 4, 5, [6]]
  • 所以要将元素移动到特定索引,我们这样做:arr.splice(index, 0, arr.splice(arr.indexOf(6), 1)[0]);
  • 也许我们也可以这样做:Array.prototype.move = function(element, index) { arr.splice(index, 0, arr.splice(arr.indexOf(element), 1)[0]); }
【解决方案2】:

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

    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 我不知道为什么我确定 OP 想要移动第一个元素 :)
  • 谢谢,但这不是我要移动的第一个元素。我正在遍历 sortedProductRow 数组/对象(?),当我找到一个具有值的属性名称“parent_product_type”时,我想将其移动到数组中的最后一个位置。这样,我的数组将只有没有属性“parent_product_type”值的对象首先出现,然后是所有具有该属性值的对象。
  • @JohanDahl 抱歉 :) 我将答案更新为更有用的内容:) 试试看。
  • 感谢您的回答!我最终使用了 Ferdi 的第二种方法,效果很好。
【解决方案3】:

这样更干净,不用[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"]

【讨论】:

    【解决方案4】:

    使用匿名函数,您可以传入数组和过滤值。

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

    此函数过滤不等于传入值的项目,然后连接另一个filter函数的结果(到过滤数组的末尾)它会过滤掉确实等于您传入的值的项目。

    此函数实质上将数组分成 2 个过滤部分,然后将它们连接在一起

    这尚未针对您的用例进行测试,但我使用了类似的方法将数组的所有数字移动到索引的末尾。

    【讨论】:

      【解决方案5】:

      将任何元素移动到最后一个位置 - 对于 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
      

      【讨论】:

        【解决方案6】:

        不可变方式:

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

        【讨论】:

          【解决方案7】:

          您可以通过splicing 移动任意数量的项目,然后将spreading 移动到push

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

          【讨论】:

            猜你喜欢
            • 2023-01-05
            • 2022-10-21
            • 2021-02-10
            • 1970-01-01
            • 2011-06-30
            • 2022-01-12
            • 1970-01-01
            • 2022-01-08
            • 2020-07-04
            相关资源
            最近更新 更多