JavaScript : Remove all duplicate elements from the internal arrays of the given 2-D array

You have to remove all duplicate elements from the internal arrays of the given 2-D array.

2-D Array

[[1,2,3,8,1,2], [54,26,14,54], [81,4,6,84]]

Internal arrays

[1,2,3,8,1,2], [54,26,14,54] and [81,4,6,84]

So the output should be something along the lines of

[[1,2,3,8],[54,26,15],[81,4,6,84]]

Code:

var twoD = [[1,2,3,8,1,2], [54,26,14,54], [81,4,6,84]];
function deleteDuplicate (twoD) {
        let uniqueArr = []; //init empty array
    for(var i=0;i<twoD.length;i++){
        for(let j of twoD[i]) {
        if(uniqueArr.indexOf(j) === -1) {   
            uniqueArr.push(j);
        }
    }
    }
     return uniqueArr;
}

console.log(deleteDuplicate(twoD));

My code returns a single array with [1,2,3,8,54,26,15,81,4,6,84] as values.

I know the issues lie in the pushing but I am unable to think of anyway, how should I do it?

Answer

You can use Set.

const arr = [[1,2,3,8,1,2], [54,26,14,54], [81,4,6,84]];


function beUnique(arr){
  const res = arr.map((a)=>{
    const unique = new Set(a);
    return Array.from(unique);
  });
  console.log(res);
}

beUnique(arr);

Leave a Reply

Your email address will not be published. Required fields are marked *