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.
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:
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.