Skip to content
Advertisement

get index of filtered array

how to get the index of filtered array?

for example I wanna to get the index of even number

  let nums = [1,2,3,4,5,6,7];

  let filterNum = nums.filter(num=> num %2 ==0);

  console.log(filterNum);

Advertisement

Answer

Use .reduce:

const nums = [1,2,3,4,5,6,7];
const filterNum = nums.reduce((acc, num, index) => {
  if(num%2 === 0) acc.push(index);
  return acc;
}, []);
console.log(filterNum);
Advertisement