piiiias piiiias - 1 month ago 8
TypeScript Question

How to find out if two Strings are the same in TypeScript?

I have an array with some strings and would like to loop through the array to check that i dont have two of the same string.

In java/javascript i would use the equals() method like below, but that dont seem to work.

array: Array<any> = [];
for(var i = 1; i < array.length; i++){
if(array[i].equals(array[i-1])){
array.splice(i);
}
}


Is there any other function or easy way to do this?

Answer

You need to use the == operator or the === operator (more info about the difference here: Which equals operator (== vs ===) should be used in JavaScript comparisons).

So:

for(var i = 1; i < array.length; i++){
  if(array[i] === array[i-1]){
    array.splice(i);
  }
}

But you need to array to be sorted for that to work.
Here's an altenative implementation:

let array = ["one", "two", "one", "three", "two", "four", "one"];

array.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
}).filter((item, index) => item !== array[index - 1]); // ["four", "one", "three", "two"]

(code in playground)


Edit

If your array contains dates then you should do:

for(var i = 1; i < array.length; i++){
  if(array[i] == array[i-1]){
    array.splice(i);
  }
}

Or

for(var i = 1; i < array.length; i++){
  if(array[i].toString() === array[i-1].toString()){
    array.splice(i);
  }
}