简体   繁体   中英

How to remove duplicates from the array of array in javascript?

I have an array let arr = [ ['A1', 'B2'], ['B1', 'A1'], ['A2','B1'], ['A1', 'B1']] . Which has duplicate ['B1', 'A1'] and ['A1', 'B1'] of different direction still it should be removed and expected output should be [ ['A1', 'B2'], ['B1', 'A1'], ['A2','B1']] . Please help me in this, thanks in advanced.

You can use Array.reduce() to get the required result, for each element in the input array we create a key .

We'll use this key to create an entry in a map object, and duplicate items will be eliminated since they will share the same key.

Once we have all items in our map, we'll use Object.values() to get the resulting (unique) array.

 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; }

You could filter with a Set with normalized values (sorted and joined).

 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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM