-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.

1
  • 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. Commented Nov 21, 2019 at 14:02

1 Answer 1

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'))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.