0

I am creating an array using Object.values(). When comparing it to a hardcoded equivalent it returns false.

var newArr = Object.values({1: 50, 2: 50, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0});
console.log(newArr); // [50, 50, 0, 0, 0, 0, 0];
var compareArr = [50, 50, 0, 0, 0, 0, 0];
console.log(compareArr); // [50, 50, 0, 0, 0, 0, 0];
console.log(newArr === compareArr); // false

Am I missing something here or should it not return true?

MLavoie
  • 9,671
  • 41
  • 36
  • 56
louis9898
  • 55
  • 6

2 Answers2

1

JavaScript compares references for non primitive types (for on == and ===). Array is not a primitive type. Meaning if they are not the same instance, the comparison will return false.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • Thank you! But using == should return true? – louis9898 Mar 10 '19 at 09:22
  • @louis9898 good point. No. I changed my answer. Comparison as a whole work the same way. The difference between == and === is that the later will not do implicit type coercion – Andre Pena Mar 10 '19 at 09:35
1

You can use JSON.stringify() to compare

var newArr = Object.values({
  1: 50,
  2: 50,
  3: 0,
  4: 0,
  5: 0,
  6: 0,
  7: 0
});
var compareArr = [50, 50, 0, 0, 0, 0, 0];
console.log(JSON.stringify(compareArr) == JSON.stringify(newArr)); // true
ellipsis
  • 12,049
  • 2
  • 17
  • 33