Home > Net >  How can I get the indexes of a filtered array items
How can I get the indexes of a filtered array items

Time:05-14

I have this situation, I have an array and I need to filter it and get the indexes of the filtered items, like this example:

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];

I'm using this filter:

var filter = arr.filter(e => e.split("-")[0] == '2022'); //To get the values from 2022

And I get this result:

filter = ['2022-05', '2022-04', '2022-02'];

What I need to do now is to get also the index of these items, so it would be this:

filter = ['2022-05', '2022-04', '2022-02'];
index = [0,2,3]

How can I do that? Thanks.

CodePudding user response:

Before filtering the array you can map it to a new array of objects that include the indexes.

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];
var output = arr.map((value, index) => ({index, value}))
  .filter(e => e.value.split("-")[0] == '2022');

console.log(output);

CodePudding user response:

when matched, just add the desired index to the array

 var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];
    
var index = [];
var filter = arr.filter((e, indx) => {
  const flag = e.split("-")[0] == '2022';
  if (flag) {
    index.push(indx)
  }
  return flag;
});
console.log(filter)
console.log(index)

CodePudding user response:

You can extract the condition check into a callback function (for simplicity), then reduce over the array and push the indexes where the condition is true into the accumulator array.

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];

const condition = (e) => e.split("-")[0] == '2022'

const filter = arr.filter(condition)
const indexes = arr.reduce((a,b,i) => (condition(b) ? a.push(i) : '', a), [])
console.log(filter, indexes)

CodePudding user response:

You could use the indexOf method:

filter.map(el => arr.indexOf(el));
  • Related