-1

Currently trying to check if two strings are permutations of one another by sorting both and checking if they are equal - permutations have the same characters, just in different orders. In my example "dog" and "god" are permutations of one another.

I have implemented the below code which I believe is correct. I made changes through looking at why this might be the case online, but I'm still stuck on why i'm getting this error as .equals() seems to be used widely to compare two strings in JavaScript.

The error is:

if (sort(s1).equals(sort(s2))) {

TypeError: sort(...).equals is not a function

function sort(string) {
  return string
    .split("")
    .sort()
    .join("");
}

function isPermutation(s1, s2) {
  if (sort(s1).equals(sort(s2))) {
    return true;
  }
  return false;
}

console.log(isPermutation("dog", "god"));
Dale K
  • 25,246
  • 15
  • 42
  • 71
mangokitty
  • 1,759
  • 3
  • 12
  • 17

5 Answers5

2

Because strings in JavaScript don't have an equals method. You compare them via ===.

Also, you can simplify your isPermutation function by returning the result of the comparison directly.

function sort(string) {
  return string
    .split("")
    .sort()
    .join("");
}

function isPermutation(s1, s2) {
  return sort(s1) === sort(s2);

}

console.log(isPermutation("dog", "god"));
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
2

You should use === to compare strings:

function sort(string) {
  return string
    .split("")
    .sort()
    .join("");
}

function isPermutation(s1, s2) {
  if (sort(s1) === (sort(s2))) {
    return true;
  }
  return false;
}

console.log(isPermutation("dog", "god"));
cccn
  • 929
  • 1
  • 8
  • 20
1

string equality in Javascript is achieved with === It might be worth looking up at the different ways Javascript handles equality as there are a few different concepts like abstract and strict equality

For example

"0" == 0 // true
"0" == "0" //true
"0" === 0 // false
"0" === "0" //true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

1

As equals don't exist in javascript.

You can register your own equals method

String.prototype.equals = function(that) {
    return this == that;
}
Umair Anwaar
  • 1,130
  • 9
  • 27
0

You can check if a value equals another by using either a "strict equality comparison" (===) or a "abstract equality comparison" (==).

So in your case you either get: if (sort(s1) === sort(s2)). or: if (sort(s1) == sort(s2)).

The main difference here is that the "abstract equality comparison" (==) will convert types before comparing. So for example 0 == "0" will return true. but 0 === "0" will return false.

Luïs
  • 2,671
  • 1
  • 20
  • 33