-4

I have an empty string array. I push into it new strings, and I do this one by one. Then, it will happen that the string I'm pushing is already in the array, and I want to find the index of that original string and split the array in the range:

[start, index_of_firstString].

So if we have:

myArray: string[] = [];

function(myString: string) {
this.myArray.push(myString);
}

What could be a good solution? I need to check for duplicates every time I push a new string.

Redriel
  • 67
  • 4
  • 10
  • 1
    You can use indexOf(): `['foo', 'bar', 'baz'].indexOf('bar'); // 1`. -1 indicates the value isn't in the array. Any other number is the index in the array. – Gavin Nov 21 '19 at 14:02

1 Answers1

4

You can use of indexOf function to get the first occurence of your string in your strings array,

var cars = ['ferrari','Audi','ferrari']

console.log(cars.indexOf('ferrari'))
Kas Elvirov
  • 7,394
  • 4
  • 40
  • 62
Fahad Subzwari
  • 2,109
  • 3
  • 24
  • 52