Comparing two equal arrays results in 'false'

Hi. I’m doing the Regex part of JS and playing a bit with the .match() method and character sets I found something that confuses me. Here is my code to show what I’ve been doing:

let quoteSample = "The quick brown fox jumps over the lazy dog.";
let alphabetRegex = /[a-il-o]/g; // Change this line
let sndAlphabetRegex = /[a-i]|[l-o]/g;
let result = quoteSample.match(alphabetRegex); // Change this
let sndResult = quoteSample.match(sndAlphabetRegex);
let isEqual = result === sndResult;
let char = [];

for (let i = 0; i < result.length; i++) {
  char.push(`${result[i]+sndResult[i]}`);
}

console.log(isEqual);
console.log(char);

My question is, why JS says that result and sndResult are not equal if contains the same elements? Sorry if my english is not good, I am learning it as well.

Short answer - you can’t do that

Mid length answer - you have to compare all of the contents

Long answer - I’m on my phone but I suspect a high quality answer is coming

2 Likes

In javascript, two primitive values are equal if they are the same. Not getting into equality vs strict equality, in primitives "Jim" == "Jim" and 247 == 247, a value comparison is done.

In non-primitive values (arrays, objects, sets, maps etc), two non-primitives are the same if they occupy the same space in memory. If i have this:

const arr1 = [1, 3, 5, -4];
// arr2 will refer to the same place in memory,
// so two variables pointing to the same thing.
const arr2 = arr1; 

console.log(arr1 == arr2)

Those are the same array, so they are equal. But this:

const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];

console.log(arr1 == arr2)

While their inside bits are the same, they’re at different memory locations. So they are not ==.

What you might want to do instead, perhaps, is compare value by value. If they are identical, then they possess the same values in the same order, and nothing more. So a for loop would let you check the primitive value in each position in both arrays for equality.

2 Likes

Ooo, a high quality one? Dang. I’ll have to wait and see what that one looks like. :stuck_out_tongue_winking_eye:

1 Like

Oh, I did not know that two non-primitives can’t be compared (except if they point to the same memory location). Thanks to help me!

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.