Robolisk
Robolisk

Reputation: 1792

finding the index of an array with indexOf with similar functionality includes

Not sure if there is something out there for this already but curious if there is, couldn't find anything in my search.

The list is always in the same order, and I need to know what the index of the element I'm trying to match is.

Here is an example:

var toSelect = 'USD';
var curr = ['USD $', 'AUD', 'CAD']; //in this example the USD has "$", but this not always true
if (curr.indexOf(toSelect)) {
  // valid
} else {
  // invalid
}

The predicament is that this curr array is delivered to me dynamically and the list of currencies is quite long, in which only 1 with have the currency symbol attached to it, and it will be random.

The problem is I always find the correct index because of the wildcard symbol (in the case the curr I want has the symbol).

Upvotes: 1

Views: 35

Answers (2)

Shiny
Shiny

Reputation: 5055

You could use .findIndex() along with the String method .includes()

var toSelect = 'USD';
var curr = ['USD $', 'AUD', 'CAD'];

let index = curr.findIndex(x => x.includes(toSelect));

console.log(index);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386604

You could take Array#findIndex with String#includes.

var toSelect = 'USD',
    curr = ['USD $', 'AUD', 'CAD']; //in this example the USD has '$', but this not always true

console.log(curr.findIndex(s => s.includes(toSelect)));

Upvotes: 2

Related Questions