简体   繁体   中英

Finding an Array within an Array using IndexOf of JavaScript

I am trying to do a very simple indexOf search without success.

I have a two dimensional Array like this:

var fruits = new Array([]);
fruits.push(["Banana", "Orange", "Apple", "Mango"]);
fruits.push(["Apple", "3Orange", "Amar", "Mango"]);
fruits.push(["Apple", "1Orange", "Amar", "Mango"]);
fruits.push(["Apple", "2Orange", "Amar", "Mango"]);

Now I am creating another Array as below which matches the third record of the above array:

var str = new Array([]);
str.push(["Apple", "2Orange", "Amar", "Mango"]);

Now I try to find if str exists in fruits:

var i  = fruits.indexOf( str );
alert(i);

But I returns -1 instead of a valid index value. What am I doing wrong?

Edit

I have figured out a very simpler way. Here is what appears to also work:

var strFruits = fruits.toString();
var newStr = str.toString();
var i  = fruits.indexOf( str );
alert(i);

This obviously has a pitfall of finding matching value across two records. But in my case I know that won't be possible because of the nature of data set that I am using. Not a good practice as a general solution but in specific cases it might be handy.

If you pass an object to Array.prototype.indexOf() , then its reference will be verified not its values. So you have to write a code like this to achieve what you want,

var str = new Array([]);
str.push(["Apple", "2Orange", "Amar", "Mango"]);
var i  = checkIt(fruits, str[0]);
alert(i);

function checkIt(src, arr){
  arr = arr.toString();
  var ind = -1;
  src.forEach(function(itm,i){
    if(itm.toString() == arr){
      ind = i;
      return;
    }
  });
  return ind;
}

DEMO

var arr1 = [1,2,3]; 
var arr2 = [1,2,3];

console.log(arr1 == arr2)   //false
console.log(arr1 === arr2)  //false

and from MDN

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

and 2 objects, even though with same internal properties, wont match.

so to match, you need to compare the array by elements inside it to match it

to compare the elements in the array, you can follow another question in SO, LINK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM