Removing duplicate values in a twodimensional array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a two-dimensional array of literals.

Our function should return a new array that contains all the entries from the original array but the repeating ones.

Example

The code for this will be −

const arr = [
   [1,2,3,4,5],
   [3,4,6,7,8,2],
   [7,2,4,9,11,15],
   [10,12,3,7,11]
];
const removeDuplicates = arr => {
   let map = {};
   let res = [];
   res = arr.map(el => {
      return el.filter(val => {
         if(map[val]){
            return false;
         };
         map[val] = 1;
         return true;
      });
   });
   return res;
};
console.log(removeDuplicates(arr));

Output

The output in the console −

[ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 11, 15 ], [ 10, 12 ] ]
raja
Published on 12-Oct-2020 11:15:10
Advertisements