1

I am most likely overlooking something something pretty basic here, but I have a really hard time figuring out why I get the following behaviour, when looking for a specific array in another array:

myArray.push(["Name", 1, 2]);
myArray.indexOf(["Name", 1, 2]);

Returns -1.. Why can't I find the array that I just pushed?

4
  • Because each time you use [] you create a new array. indexOf compares references. Commented Sep 21, 2016 at 6:39
  • That makes sense. Can you give me heads up on how to achieve the behaviour im looking for? Commented Sep 21, 2016 at 6:41
  • 1
    Possible duplicate of javascript search array of arrays Commented Sep 21, 2016 at 6:45
  • This seems to be a duplicated question. Here is the link to a quit similar problem: stackoverflow.com/questions/24943200/… Commented Sep 21, 2016 at 6:47

2 Answers 2

1

Try this:

var myArray = [];
var anotherArray = ["Name", 1, 2];

myArray.push(anotherArray);
myArray.indexOf(anotherArray);  // returns 0
Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

var checkArray = ["Name", 1, 2]
var myArray = [];

myArray.push(checkArray);
myArray.indexOf(checkArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.