0

Hi this is probably an easy question. So I want to make a basic anagram function in Javascript.

The following snippet does not work

anagrams = (phraseOne, phraseTwo) => {
    if (phraseOne.split("").sort() === phraseTwo.split("").sort()) {
        return true  
    } else {
        return false
    } 
}

However this does work

anagrams = (phraseOne, phraseTwo) => {
    if (phraseOne.split("").sort().join("") === phraseTwo.split("").sort().join("")) {
        return true  
    } else {
        return false
    } 
}

Why? The arrays are identical before you join("") them

Fpzzzz
  • 1
  • 1
  • 1
    Can you give which inputs pass the first snippet but not the second one? – sp00m Jul 18 '19 at 09:49
  • @sp00m every given input. – Jonas Wilms Jul 18 '19 at 09:49
  • `.join` will convert the array back to the same string – Krishna Prashatt Jul 18 '19 at 09:50
  • @JonasWilms Oh, I read the question the opposite way, I thought #1 was passing and #2 failing ;) So yeah, duplicates the one you linked. – sp00m Jul 18 '19 at 09:51
  • The `==` operator for Objects in Javascript only checks to see if the objects are the same actual object reference, not if they are two separate object that contain the same contents. According to the [chart](https://dorey.github.io/JavaScript-Equality-Table/) `[] == []` gives us false. So the second `anagram` works because it compares strings rather than objects. – shrys Jul 18 '19 at 09:57

1 Answers1

1

That's because strings are compared by value and arrays are compared by reference in JS. You can find out more about comparison here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Clarity
  • 10,730
  • 2
  • 25
  • 35