How to skip elements in array using map function and return single value

Viewed 25

I have an array of userid and I want to map through them and get the index of a single userid that matches. How do I do that?

const userid = [ "user1", "user2", "user3" ]

userid.map((user,index) => {
   if(user === "user2") return index
}

Expecting output

[1]

Actual Output

[undefined,1,undefined]
1 Answers

.map is create a new array with the same number of items. If you want to loop over an array and do some things you can try .reduce instead. Like this:

const userid = [ "user1", "user2", "user3" ]

const condition = (x) => x === 'user2';
const result = userid.reduce((pre, cur, index) => condition(cur) && [...pre, index] || pre, []);

console.log(result); // [1]

in your case, you can use .findIndex:

const userid = [ "user1", "user2", "user3" ]

const condition = (x) => x === 'user2';
const result = userid.findIndex(x => condition(x));
console.log(result); // 1

Related