0

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.

1 Answer 1

1

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 ) };
Sign up to request clarification or add additional context in comments.

7 Comments

If all you're doing is an equality check in the findIndex test you can also just use indexOf: names.indexOf( valToFind )
@Paulpro yeah, this is much simpler if the values are going to be a primitive value. Thanks.
Yes we can, But somehow can I return both using callback?
@SanjayShr return to whom?
To the variable. I ended up using one more array like this. var names = ['A', 'B', 'C', 'D', 'E', 'F', 'G']; let res=[]; const name = names.filter((name, index) => name === 'C' ? res.push(index, value): null)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.