Home > OS >  What is the best way to check multidimensional array in typescript or javascript to detect duplicate
What is the best way to check multidimensional array in typescript or javascript to detect duplicate

Time:04-06

I have two dimensional array like below:

  array =  [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ]

I want to compare value in array index to see if they have duplicate values. For example

 array[0] = [1,1];
 array[1] = [1,2];
 array[2] = [1,1];

We can see that value at index 0 and 2 are same that is [1,1]. So, in that case I want to have true flag. What is the most efficient way to do it? or What are different ways to do it? Any kind of suggestion or help would be great with bit of explanation. Thanks in advance.

CodePudding user response:

So, what I think you can do is:

  1. Cycle every element of the multidimensional array.
  2. Then check if the two element are the same by accessing the "row" with the index 0 and index 1

I think you can use different way to loop the array, this is what I tried:

// DECLARATIONS
array =  [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];

// LOOPING THE ARRAY 
for (row of array)
{
  // RETURN TO CONSOLE OR WHATEVER THE BOOLEAN VALUE
  console.log(row[0] == row[1]);
}

CodePudding user response:

You can achieve it by convert the inner array elements into a string just for the comparison purpose.

Demo :

const arr = [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];

const stringConversion = arr.map((item) => JSON.stringify(item))

const duplicateElements = stringConversion.filter((item, index) => stringConversion.indexOf(item) !== index)

console.log(duplicateElements.length ? true : false);

  • Related