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]);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
TribeOfOne
  • 173
  • 9

4 Answers4

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);
axtck
  • 3,707
  • 2
  • 10
  • 26
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
Guerric P
  • 30,447
  • 6
  • 48
  • 86
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
maziyank
  • 581
  • 2
  • 10
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

Mikhail Grechka
  • 717
  • 2
  • 10