Reputation: 2152
I tried with filter()
function but I'm not sure about returning index and value using that. here's sample code that I tried.
var names = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
const name = names.filter((name, index) => name === 'G' ? console.log(${index}: ${name}) : null)
here variable name
is useless because on call back I'm returning nothing.
However, I can access index
and name
inside callback but not sure about returning both.
Upvotes: 0
Views: 262
Reputation: 68393
Use findIndex
instead
var names = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
var valToFind = "G";
const valIndex = names.findIndex( s => s === valToFind );
you already know that the value is valToFind
, so no need to return it.
Or as @PaulPro pointed out, if the values are just strings, then simply use
const valIndex = names.indexOf( valToFind );
Or you can wrap it in an object
var output = { name : valToFind, index : names.indexOf( valToFind ) };
Upvotes: 1