将数组中的项目移到最后一个位置 [英] Move item in array to last position
问题描述
我有一个对象数组.我想将选定的对象移动到数组中的最后一个位置.如何在javascript或jquery中做到这一点?
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?
这里有一些代码:
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"值的对象首先出现,然后是那些具有值的对象.
I'm looping through this with a for loop, and I want the output to be ordered so that all objects that does not have a "parent_product_type" value comes first, then those with a value.
推荐答案
要将元素(您知道索引)移动到数组的末尾,请执行以下操作:
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]);
示例:
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()
)
this only works with Arrays (created with the [ ... ]
syntax or
Array()
) not with Objects (created with the { ... }
syntax or
Object()
)
这篇关于将数组中的项目移到最后一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!