Two identical arrays returning false when compared

Asked

Viewed 72 times

0

I need help with this code that doesn’t seem to make sense. I have debugged and the values given up to the penultimate line are:

splited = ["i","s","o","g","r","a","m"]

unique = ["i","s","o","g","r","a","m"]

str = 'isogram'
var splited = str.split('');
let unique = [...new Set(splited)];
if(splited == unique){return true} else {return false}; // retorna false
  • 1

    arrays are objects, they are not the same, they are similar, just as two oranges are similar.. , what you compare in the array to see if it is the same is its size and content

  • 1

    Each time you are comparing two arrays, you are actually comparing the reference in the memory of both, so it will always give 'false'. For they are two different instances.

2 answers

3


When working with Arrays and Objects, keep in mind that you always manipulate a variable reference, not its value itself. I’ll leave an article explaining below:

https://braziljs.org/artigos/diferencas-entre-valor-e-referencia-em-javascript/

To compare array, use the following code:

Function:

// Warn if overriding existing method
if(Array.prototype.equals)
    console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time 
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].equals(array[i]))
                return false;       
        }           
        else if (this[i] != array[i]) { 
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;   
        }           
    }       
    return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});

Utilizing:

[1, 2, [3, 4]].equals([1, 2, [3, 2]]) === false;
[1, "2,3"].equals([1, 2, 3]) === false;
[1, 2, [3, 4]].equals([1, 2, [3, 4]]) === true;
[1, 2, 1, 2].equals([1, 2, 1, 2]) === true;

Reference: https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript

-1

When working with Array the correct and always see the length then you could make the following comparison:

splited.length == unique.length  (true)
  • 4

    It is also necessary to compare the content as the condition: "[1, 2, 3]. length === [4, 5, 6]. length" would return true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.