0

Why are the last two console.logs showing false?

const a = 'one';
const b = 'two';
const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];
console.log([a, b]);
console.log(myArray[0]);
console.log(myArray.includes([a, b]));
console.log(myArray[0] === [a, b]);

1
  • 1
    You should post your code as a snippet in your question Commented Feb 26, 2021 at 13:19

4 Answers 4

2

in JavaScript arrays and objects are compared by reference and not by value.

One solution I suggest is to use JSON.stringify()

a = ["a", "b"]
b = ["a", "b"]

console.log(JSON.stringify(a) == JSON.stringify(a)) // return true

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

Comments

2

Array.prototype.includes() and triple equal operator === work with references, they don't compare the elements of the arrays, they compare the array references themselves:

console.log([] === []); // false

const a = [];
const b = a;

console.log(a === b); // true

Comments

2

You could first convert the array (object) to a string using JSON.stringify(), then compare the string:

const a = 'one';
const b = 'two';
const myArray = [
  ['one', 'two'],
  ['three', 'four'],
  ['five', 'six']
];

console.log(JSON.stringify(myArray[0]) === JSON.stringify([a, b]));

You can also run through the separate values using every() and compare them like this:

const a = 'one';
const b = 'two';
const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];

const isequal = [a, b].length === myArray[0].length && [a, b].every((value, i) => value === myArray[0][i]);
console.log(isequal);

2 Comments

That's great if you know it's in the array and what index it's at.
Yes indeed they would have to be in the right order
1

Arrays in JavaScript are Objects and Objects comparison will always return false if the referenced objects aren't the same.

If you want to compare arrays you have to write a function for this or use isEqual func from lodash

https://lodash.com/docs/4.17.15#isEqual

2 Comments

"always return false" is only true for NaN, not for objects.
Objects comparison will always return false No, objects comparison will return true if the referenced object is the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.