Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading