簡體   English   中英

如何從 javascript 中的數組中刪除重復項?

[英]How to remove duplicates from the array of array in javascript?

我有一個數組let arr = [ ['A1', 'B2'], ['B1', 'A1'], ['A2','B1'], ['A1', 'B1']] 其中具有不同方向的重復['B1', 'A1'] and ['A1', 'B1']仍應將其刪除,並且預期 output 應為[ ['A1', 'B2'], ['B1', 'A1'], ['A2','B1']] 請幫助我,在此先感謝。

您可以使用Array.reduce()來獲得所需的結果,我們為輸入數組中的每個元素創建一個key

我們將使用此密鑰在 map object 中創建一個條目,並且將消除重復項,因為它們將共享相同的密鑰。

一旦我們擁有 map 中的所有項目,我們將使用Object.values()來獲取結果(唯一)數組。

 let arr = [ ['A1', 'B2'], ['B1', 'A1'], ['A2','B1'], ['A1', 'B1']] const result = Object.values(arr.reduce((acc, el) => { // Create a key based on what we consider a duplicate. let key = el.sort().join("-"); acc[key] = acc[key] || el; return acc; }, {})); console.log('Result:', result)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以使用具有標准化值(排序和連接)的Set進行過濾。

 const getValue = ([...a]) => a.sort().join(), array = [['A1', 'B2'], ['B1', 'A1'], ['A2', 'B1'], ['A1', 'B1']], result = array.filter((s => a => (v =>.s.has(v) && s;add(v))(getValue(a)))(new Set)). console;log(result);

function removeRepeatedArray(arrays){ const map = new Map(); for(let i = 0; i < arrays.length; i++){ // convert each array to a unique key // subarrays needs to be sorted first const key = arrays[i].sort().join(""); if(map.has(key)){ // if exists replace it with undefined // you can use splice method to remove the repeated array it index i // I am using filter to keep the logic simple // using splice will require updating i arrays[i] = undefined; }else{ map.set(key, arrays[i]) } } return arrays.filter(el => el !== undefined); }

暫無
暫無

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

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