Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Indexes of Filtered Array Items

In JavaScript, I have the following array

var arr = [5, 10, 2, 7];

From that array, I would like to get an array containing only the indexes of the items that are less than 10. So, in the above example, the indexes array would be

var indexes = [0, 2, 3];

Now, I want something simlar to filter, but that would return the indexes.

If I try filter, this is how it will work

var newArr = arr.filter(function (d) {
    return (d < 10);
});

// newArr will be: [5, 2, 7];

This is not what I want. I want something along the following lines (note this is a pseudo-code)

var indexes = arr.filter(function (d) {
    /* SOMETHING ALONG THE FOLLOWING PSEUDOCODE */
    /* return Index of filter (d < 10); */
});

// indexes will be: [0, 2, 3];

How can I do that? Thanks.

like image 277
Greeso Avatar asked Dec 21 '17 03:12

Greeso


3 Answers

Use a reducer.

var arr = [5, 10, 2, 7];

var newArr = arr.reduce(function(acc, curr, index) {
  if (curr < 10) {
    acc.push(index);
  }
  return acc;
}, []);


console.log(newArr);
like image 71
Oluwafemi Sule Avatar answered Oct 04 '22 18:10

Oluwafemi Sule


You can use a forEach loop:

const arr = [5, 10, 2, 7];


const customFilter = (arr, min) => {
  const result = [];
  arr.forEach((element, index) => {
    if (element < min) {
      result.push(index);
    }
  });
  
  return result;
}

console.log(customFilter(arr, 10));
like image 4
klugjo Avatar answered Oct 02 '22 18:10

klugjo


You can use array#reduce and add indexes whose value is greater than 10.

var arr = [5, 10, 2, 7];
var indexes = arr.reduce((r, d, i) => d < 10 ? (r.push(i), r) : r , []);
console.log(indexes);
like image 2
Hassan Imam Avatar answered Oct 01 '22 18:10

Hassan Imam