我在这里编写了一些代码来添加一个元素到数组中,具体逻辑如下:
如果该元素已经存在于数组中,则函数应该从数组中删除该元素并返回不包含该元素的数组,否则它应该将该元素附加到数组中并返回整个数组。
考虑到这一点,我在想是否有更好的方法来实现这个功能。以下是我编写的代码。
function filterArray(arr, obj, key) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === obj[key]) {
const newArr = [...arr]
newArr.splice(i, 1)
return newArr
}
}
return [...arr, obj]
}
const fruits = [
{ id: 1, fruit: "Apple" },
{ id: 2, fruit: "Banana" },
{ id: 3, fruit: "Pineapple" }
]
const removedBanana = filterArray(fruits, {
id: 3,
fruit: "Banana"
}, "fruit")
const addedStrawberry = filterArray(fruits, {
id: 4,
fruit: "Strawberry"
}, "fruit")
console.log(removedBanana) // [ { id: 1, fruit: 'Apple' }, { id: 3, fruit: 'Pineapple' } ]
console.log(addedStrawberry)
// [
// { id: 1, fruit: 'Apple' },
// { id: 2, fruit: 'Banana' },
// { id: 3, fruit: 'Pineapple' },
// { id: 4, fruit: 'Strawberry' }
// ]
在ES6中有更好的方法可以做到这一点吗?
编辑
如果可能的话,我想只迭代一次数组,达到O(n)的算法。