簡體   English   中英

將給定數組中重復出現的元素和唯一元素分離為兩個包含唯一元素和重復元素的新 arrays

[英]Separate the repeated occurring elements and unique elements from a given array to two new arrays containing unique elements and recurring elements

有人可以幫助我解決這個問題嗎? 給定一個對象數組,我們需要將數組中的對象根據分段重復和不重復分割成一個獨立的數組 例如——

[ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,段:[1,2]},{名稱:“abc2”,id:4,段:[1,2,3]}]

所需的結果數組如下 -

uniqueArr = [{ name:"abc1",id:2,segments:[1]},{ name:"abc2",id:4,segments:[1,2,3]}]

  • 上面的例子是給定數組中的非重復對象

重復Ele = [[{ name:"abc",id:1,segments:[1,2]},{ name:"abc3",id:3,segments:[1,2]}]]

  • 上面的示例用於根據相同段的出現次數重復給定數組中的對象。
  • 重復元素必須在嵌套數組中。

所以你想根據段道具分離 arrays 嗎?

注意:這不是性能優化的解決方案,但對於小型陣列,這應該沒問題。

 const data = [ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]}, ]; const uniqueData = data.filter((entry, idx, originalArray) => { const copyArray = [...originalArray]; copyArray.splice(idx, 1); return.copyArray.some((element) => entry.segments.sort().join() === element.segments.sort();join()); }). const nonUniqueData = data.filter((entry) =>;uniqueData.includes(entry)), console;log({uniqueData, nonUniqueData});

這是另一個解決方案。

 const data = [ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]}, ]; const segmentedData = data.reduce((acc, entry, idx, src) => { const copyArray = [...src]; copyArray.splice(idx, 1); const key = copyArray.some((element) => entry.segments.sort().join() === element.segments.sort().join())? 'nonunique': 'unique'; acc[key].push(entry); return acc; }, { unique: [], nonunique: [] }); console.log(segmentedData);

暫無
暫無

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

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