-1

I have a condition set up in typescript which compares 2 variables:

this.CurrentSelection == this.PreviousSelection

Both variables are arrays and can be an empty array ([]). In my app, I have a condition where each of these variables is an empty array (Array(0) in CDT watch). When the comparison happens between these 2 empty arrays, the result is false. It seems like [] == []. Any idea about the underlying reason for this? Do I need an additional "or" clause to check for length==0 for this scenario?

user8334943
  • 1,467
  • 3
  • 11
  • 21

1 Answers1

0

You're comparing references. The result will only be true if both a and b reference the same array:

const a = [];
const b = [];
const c = a;

console.log(a === b);
console.log(a === c);

If you want to check if both arrays contain the same values, you could do something like this:

function arrayEquals(a, b) {
  return a.length === b.length && a.every((v, i) => v === b[i]);
}

console.log(
  arrayEquals([1,2,3], [1,2,3])
);
SimpleJ
  • 13,812
  • 13
  • 53
  • 93