簡體   English   中英

Javascript ES6,如果存在則從數組中刪除項目或如果不存在則添加的最佳方法

[英]Javascript ES6, best way to remove item from array if it exists or add if doesn't exists

我在這里編寫了一些代碼,以使用以下邏輯在數組上添加一個元素

如果該元素存在於數組中,則函數應從數組中刪除該元素並返回沒有給定元素的數組,否則應返回附加了給定元素的數組。

考慮到這一點,我在想是否有更好的方法來做到這一點,這是我為此編寫的代碼。

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

這種方法通過查找索引和拼接(如果找到)或將對象推送到數組來改變數組。 結果與傳遞的數組具有相同的對象引用。

 function filterArray(array, object, key) { var index = array.findIndex(o => o[key] === object[key]); if (index === -1) array.push(object); else array.splice(index, 1); return array; } const fruits = [{ id: 1, fruit: "Apple" }, { id: 2, fruit: "Banana" }, { id: 3, fruit: "Pineapple" }]; console.log(filterArray(fruits, { id: 3, fruit: "Banana" }, "fruit")); console.log(filterArray(fruits, { id: 4, fruit: "Strawberry" }, "fruit"));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

對於非變異方法,您可以在函數的頭部獲取一個副本並執行與上述相同的操作。

function filterArray([...array], object, key) {

 function filterArray(array, object, key) { var index = array.findIndex(o => o[key] === object[key]); if (index === -1) array.push(object); else array.splice(index, 1); return array; } const fruits = [{ id: 1, fruit: "Apple" }, { id: 2, fruit: "Banana" }, { id: 3, fruit: "Pineapple" }]; console.log(filterArray(fruits, { id: 3, fruit: "Banana" }, "fruit")); console.log(filterArray(fruits, { id: 4, fruit: "Strawberry" }, "fruit"));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

您可以使用Array.some()來檢查對象是否存在,以及是否將其過濾掉。 如果沒有,請添加它。

 function filterArray(arr, obj, key) { return arr.some(o => obj[key] === o[key]) ? // if you can find the object arr.filter(o => obj[key] !== o[key]) // remove it : [...arr, obj] // or add it if not } 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' } // ]

這個問題有一個簡單的解決方案:

function addObjToArray (arr, obj, key) {
  const resultArr = arr.filter(arrObj => arrObj[key] !== obj[key])
  if (resultArr.length === arr.length) resultArr.push(obj)
  return resultArr
}

filter方法將返回一個數組,其中包含與obj[key]不同的obj[key] 如果過濾后的數組等於原始數組,則將對象推送到resultArr ,否則,只返回初始resultArr

這是我同事的解決方案( https://stackoverflow.com/users/12691758/guilherme-ca%c3%a7ador-monteiro )。

你認為呢?

根據您的要求,以及附加要求——在評論中——集合應該mutate ,通過使用 ES6 Map ,您將擁有更好的工具:

 const fruits = new Map([ { id: 1, fruit: "Apple" }, { id: 2, fruit: "Banana" }, { id: 3, fruit: "Pineapple" } ].map (o => [o.fruit, o])); fruits.key = "fruit"; // register the key field once fruits.toggleItem = function (obj) { if (!this.delete(obj[this.key])) this.set(obj[this.key], obj); } fruits.toggleItem({id: 3, fruit: "Banana"}); console.log([...fruits.values()]); fruits.toggleItem({id: 4, fruit: "Strawberry"}); console.log([...fruits.values()]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM