1

I am using javascript to compare a single array and a multidimensional array. Here i want to compare those 2 array and the matched value should be shown.

  • arr[1,2,3] value to be searched in multidimensional array " md2 ".

This is my Code :: i have taken an single array and other as multidimensional array

var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
  if(arr == md2[j]){
    console.log(arr + " ... " + md2[j]);
  }
}

Required O/P :- [1,2,3] should match and should be displayed in the console

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Khauri Feb 03 '19 at 16:35

4 Answers4

0

You can use .find() and .every() methods to find array inside multi-dimensional array:

var arr1 = [1,2,3];
var arr2 = [1,2,5];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];

var searchAndPrint = (a1, a2) => {
  let arr = a1.find(a => a.every((v, i) => v === a2[i]));
  
  if(arr)
    console.log(arr);
  else
    console.log("No Results");
};

searchAndPrint(md2, arr1);
searchAndPrint(md2, arr2);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

You can't compare arrays in js. If you wanna compare simple arrays you can convert them to string to compare. This method is not applicable to array containing objects.

var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
  if(arr.toString() === md2[j].toString()){
    console.log(arr + " ... " + md2[j]);
  }
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use JSON.stringify to compare the arrays.

var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
  if(JSON.stringify(arr) === JSON.stringify(md2[j])){
    console.log(arr + " ... " + md2[j]);
  }
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

For checking, you need to check the length and the items directly, because you have no same object reference.

var arr = [1, 2, 3],
    md2 = [[23, 8, 2], [1, 5, 8], [1, 2, 3], [8, 5, 2]];
    
console.log(md2.some(a => arr.length === a.length && a.every((v, i) => v === arr[i])));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392