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

标签 javascript arrays sorting

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

最佳答案

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

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]

NOTE:

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

关于javascript - 将数组中的项目移动到最后一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909371/

相关文章:

javascript - Canvas 图像消失

javascript - jQuery:获取图像加载错误的详细信息

java - 将Java字节数组转换为Go结构

php - 如何用 PHP 对数组进行排序,忽略开头的冠词 (a, an, the)?

java - 如何在Java中根据两列的值对二维数组进行排序

javascript - 刷新页面的一部分(div)

javascript - 运行混合内容有什么解决方法吗?

python - 在 Python 中遍历多维数组

c# - 按数组中定义的顺序对字符串列表进行排序的有效方法?

java - Java 中的 ArrayList 排序