1

I am wondering how you would go about deleting arrays that contain the same elements in a 2 dimensional array.

For example:

let 2dArr = [ [1, 2, 3],
              [3, 2, 1],
              [2, 4, 5],
              [4, 5, 2],
              [4, 3, 1] ];

This array would delete the second and fourth elements, returning the 2d array:

returnedArr = [ [1, 2, 3],
                [2, 4, 5],
                [4, 3, 1] ];

How exactly could this be done, preserving the 2d array? I could only think to loop through elements, comparing elements via a sort, and deleting them as you go along, but this would result in an indexing error if an element is deleted.

0

4 Answers 4

6

1) You can easily achieve the result using reduce and Set as:

let twodArr = [
  [1, 2, 3],
  [3, 2, 1],
  [2, 4, 5],
  [4, 5, 2],
  [4, 3, 1],
];

const set = new Set();

const result = twodArr.reduce((acc, curr) => {
  const key = [...curr].sort((a, b) => a - b).join();
  if (!set.has(key)) {
    set.add(key);
    acc.push(curr);
  }
  return acc;
}, []);

console.log(result);

2) You can also use filter as:

let twodArr = [
  [1, 2, 3],
  [3, 2, 1],
  [2, 4, 5],
  [4, 5, 2],
  [4, 3, 1],
];

const set = new Set();

const result = twodArr.filter((curr) => {
  const key = [...curr].sort((a, b) => a - b).join();
  return !set.has(key) ? (set.add(key), true) : false;
});

console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

Need numeric sort. Works fine here only because all are single digit
@charlietfl modified the code. Thanks for pointing out the mistake...
Just an oversight, never a mistake!
1
const seen = []

const res = array.filter((item) => {
  let key = item.sort().join()
  if(!seen.includes(key)){
    seen.push(key)
    return item
  }
})

console.log(res)

Comments

0

You can use hash map

let arr = [ [1, 2, 3], [3, 2, 1],[2, 4, 5],[4, 5, 2],[4, 3, 1] ];
let obj = {}
let final = []

for(let i=0; i<arr.length; i++){
  // create a key
  let sorted = [...arr[i]].sort((a,b)=> a- b).join`,`
  // check if this is not present in our hash map
  // add value to final out and update hash map accordingly
  if(!obj[sorted]){
    obj[sorted] = true
    final.push(arr[i])
  }
}

console.log(final)

Comments

0

Using Array.prototype.filter() and a Set as thisArg

let arr = [ [1, 2, 3],
              [3, 2, 1],
              [2, 4, 5],
              [4, 5, 2],
              [4, 3, 1] ];


let res = arr.filter(function(e){
    const sorted = [...e].sort((a,b) => a-b).join('|');
    return this.has(sorted) ? false : this.add(sorted)    
},new Set)

console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.