0

These codes don't work:

const a = [[1, 1], [2, 2]]
console.log(a.includes([1, 1])); // --> false
console.log(a.indexOf([1, 1])); // --> -1

This work but I think its not optimized

console.log(a.map(x => x.toString()).includes([1, 1].toString()));
// --> true

Is there a simpler way ?

6
  • 1
    this might also help: stackoverflow.com/questions/7837456/… (if [1, 1] are the same reference in memory, then you can find your result using the first two methods) Commented Aug 19, 2019 at 10:26
  • Array is one kind of object, both the objects are referring to a different location from the addressing point of view. Compare each element one by one. Commented Aug 19, 2019 at 10:29
  • JSON.stringify(a).includes('[1,1]') Commented Aug 19, 2019 at 11:16
  • Thanks for all answers Commented Aug 19, 2019 at 11:26
  • use a.join(".").indexOf([1, 1]) for optimized solution Commented Aug 19, 2019 at 11:27

2 Answers 2

0

const a = [[1, 1], [2, 2]]
var index=a.findIndex(x=>{return JSON.stringify(x)===JSON.stringify([2, 2])})

console.log(`item index : ${index}`);

Sign up to request clarification or add additional context in comments.

Comments

-2

Assuming this:

var arr = ['a', 'b', 'b'];

you can invoke:

Array.isArray(arr);

will return true if the considered variable is an array, otherwise not.

Once you get it, you can apply it to the external array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.