JS – How to find unique elements inside a 2D-Array?

Advertisements

In the code below, I am checking how many unique elements are in a row.
How can I rewrite the code to check how many unique elements are in a column? For example, in the first column, the result would be: (i = 0) uniqueElements = 3 ( E, F, B )

let arr = [["E", "D", "E", "E", "C"],
           ["E", "A", "C", "E", "C"],
           ["F", "B", "C", "D", "G"],
           ["B", "C", "G", "G", "F"],
           ["E", "C", "E", "B", "C"]];

for (let i = 0; i < arr.length; i++) {
  
  // Check unique Elements in Rows
  let uniqueElements = arr[i].filter((elem, index) => arr[i].indexOf(elem) === index).length;

  // (i = 0) uniqueElements = 3 ( E, D, C ) 
  // (i = 1) uniqueElements = 3 ( E, A, C )
  // (i = 2) uniqueElements = 5 ( F, B, C, D, G )
  // (i = 3) uniqueElements = 4 ( B, C, G, F )
  // (i = 4) uniqueElements = 3 ( E, C, B )
}

>Solution :

You can use a Set to get unique elements in array:

let arr = [["E", "D", "E", "E", "C"],
           ["E", "A", "C", "E", "C"],
           ["F", "B", "C", "D", "G"],
           ["B", "C", "G", "G", "F"],
           ["E", "C", "E", "B", "C"]];

for (let i = 0; i < arr.length; i++) {
  const mySet = new Set(arr[i])
  console.log(`uniqueElements: ${mySet.size}`)
  console.log(mySet.values())
}

Leave a Reply Cancel reply