【发布时间】:2021-05-15 02:12:29
【问题描述】:
我有一个具有这种格式的对象数组
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
现在我基本上想通过重新排列将带有 6 的项目移动到数组的前面,这样结果就变成了
let result = [ { name: "test2", id: 6 } , { name: "test1", id: 5}, { name: "test3", id: 8 } ]
我尝试过的
const found = arr.find((element) => {
return element.id === 6;
});
if (found) {
const [...arr, found] = arr;
return found;
} else {
return arr;
}
【问题讨论】:
-
使用
.splice()删除该项目,然后使用.unshift()将其添加到前面。
标签: javascript arrays ecmascript-6 ecmascript-5