簡體   English   中英

從對象數組中的嵌套數組中刪除重復項

[英]Remove duplicates from nested array in array of objects

我有這個對象數組:

const arrayOfObjects = [{
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000]
  },
  {
    id: 20,
    children: [2000]
  },
];

我想使用以下代碼刪除重復項:

  const arrayHashMap = arrayOfObjects.reduce((obj, item) => {
    if (obj[item.id]) {
      // obj[item.id].children.push(...item.children);
      const temporaryArray = [...obj[item.id].children, ...item.children];
      obj[item.id].children = [...new Set(temporaryArray)];
    } else {
      obj[item.id] = {
        ...item
      };
    }
    return obj;
  }, {});
  const result = Object.values(arrayHashMap);

在這段代碼中,我注釋了將值推送到數組的部分。 我嘗試使用“new Set”從最終數組中刪除重復項,但我總是將值分配給“obj[item.id].children”。 這可以嗎還是有更好的方法來寫這個?

預期結果:

[{
  id: 10,
  children: [1000, 2000]
}, {
  id: 20,
  children: [1000, 2000]
}]

謝謝

如果值不存在,您可以按id分組並檢查數組,然后推送該值。

 const data = [{ id: 10, children: [1000] }, { id: 10, children: [2000] }, { id: 20, children: [1000] }, { id: 20, children: [1000, 2000] }, { id: 20, children: [2000] }], result = Object.values(data.reduce((r, { id, children }) => { r[id]??= { id, children: [] }; children.forEach(v => { if (.r[id].children.includes(v)) r[id].children;push(v); }) return r, }; {})). console;log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

我不知道“更好”,但也許更簡潔:

 const arrayOfObjects = [{ id: 10, children: [1000] }, { id: 10, children: [2000] }, { id: 20, children: [1000] }, { id: 20, children: [1000, 2000] }, { id: 20, children: [2000] }, ]; const arrayHashmap = arrayOfObjects.reduce((obj, { id, children }) => ({...obj, [id]: { id, children: [...new Set([...obj[id]?.children?? [], ...children ])] } }), {}) const result = Object.values(arrayHashmap); console.log(result)

編輯:哎呀,“整潔”按鈕改變了語義。 固定的。

使用Array#prototype#reduce減少數組並在 children 屬性上初始化一個集合,並繼續添加到集合中,最后將 map 集合回數組。

 const arrayOfObjects = [{ id: 10, children: [1000] }, { id: 10, children: [2000] }, { id: 20, children: [1000] }, { id: 20, children: [1000, 2000] }, { id: 20, children: [2000] }, ]; const result = Object.values( arrayOfObjects.reduce((r, c) => { r[c.id] = r[c.id] || { id: c.id, children: new Set() }; c.children.forEach((item) => r[c.id].children.add(item)); return r; }, Object.create(null)) ).map((x) => ({ id: x.id, children: [...x.children] })); console.log(result);

 const arr = [ { id: 10, children: [1000], }, { id: 10, children: [2000], }, { id: 20, children: [1000], }, { id: 20, children: [1000, 2000], }, { id: 20, children: [2000], }, ]; let result = arr.reduce((acc, i) => { let obj = acc.find((a) => a.id === i.id); obj? (obj.children = [...new Set(obj.children.concat(i.children))]): acc.push(i); return acc; }, []); console.log(result);

你可以試試這個小提琴: https://jsfiddle.net/d0kboywv/2/

const arrayOfObjects = [
  {
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000, 3000]
  },
  {
    id: 20,
    children: [2000, 4000]
  },
];

let mappedArray = new Map(arrayOfObjects.map(o => [o.id, {}] ));
for (let obj of arrayOfObjects) {
    let child = mappedArray.get(obj.id);
    for (let [key, val] of Object.entries(obj.children)) {
        child[key] = (child[key] || new Set).add(val);
    }
}
let result = Array.from(mappedArray.entries(), ([id, child]) => ({ 
    id, 
    children: [...new Set(Object.entries(child).map(([k, v]) => 
        [...v]
    ).reduce((a, b) => a.concat(b), []))].sort()
}));
console.log(result);

它為我完成了這項工作!

您可以臨時將數據結構轉換為更簡單

常量 objectOfArray = {}; 你的身份是關鍵,你的孩子是價值

我使用名稱 initialData 來引用您的數組

  const objectOfArray = {};
  initialData.forEach(e => {
    if (objectOfArray[e.id] {
      objectOfArray[e.id].push(...e.children);
    } else {
      objectOfArray[e.id] = [...e.children];
    }
  });


  const result = Object.entries(objectOfArray).map(([id, children]) => {
    return {
      id,
      children: children.filter((e, i) => i === chilren.indexOf(i)),
    }
  });

您還可以通過運行以下代碼來實現預期的 output

makeMapping = {};
for (let obj of arrayOfObjects) {
    makeMapping[obj.id] = {...obj, children: [...new Set([...obj.children, ...(makeMapping[obj.id]?.children || [])])]};
}
console.log(Object.values(makeMapping));

暫無
暫無

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

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