Home > Software engineering >  JS - How to find unique elements inside a 2D-Array?
JS - How to find unique elements inside a 2D-Array?

Time:01-10

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 )
}

CodePudding user response:

You can use a Set to get unique elements of rows in matrix:

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())
}

If you want to get a Set of columns in matrix:

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"]];

let columnSets = [];

for (let i = 0; i < arr[0].length; i  ) {
  let column = arr.map(row => row[i]);
  let columnSet = new Set(column);
  columnSets.push(columnSet);
}

console.log(columnSets);

CodePudding user response:

The code has been saved as much as possible.

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);
  console.log(`(i = ${i}) uniqueElements = ${uniqueElements.length} (${uniqueElements})`);

  // (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 )
}
  • Related