ket
ket

Reputation: 11

How to return indices from javascript filter function (filtered based on values)?

I want to do something that seems simple but I cannot figure it out. I want to use the javascript function 'filter' to find values in an array greater than a value and then return the indices that correspond the those filtered values (or values in that indice range from another array.

arr1 = [1,3,7,9,11];
arr1 = [2,4,8,10,12];
arr1.filter(x => x > 7);
// returns: [9,11]
// desired return: [4,5] (indices from arr1 where values from arr1 that were filtered) and/or [10,12]  
// (values from arr2 where values from arr1 that were filtered)

I know the code is not right but I cannot figure out how to get desired result. Any help would be appreciated. Thanks

Upvotes: 1

Views: 1221

Answers (5)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

Just add another map call and indexOf
PS: If there are duplicate values, indexOf return only first occurrence.

Alternatively, if you are not particular about filter, you can use reduce which can done with one iteration.

const arr1 = [1,3,7,9,11];
const arr2 = [2,4,8,10,12];

const filter = arr => arr.filter(x => x > 7).map(x => arr.indexOf(x));

console.log(filter(arr1))
console.log(filter(arr2))

const filter2 = arr => arr.reduce((acc, x, i) => (x > 7 && acc.push(i), acc), []);
console.log(filter2(arr1))
console.log(filter2(arr2))

Upvotes: 0

Heretic Monkey
Heretic Monkey

Reputation: 12113

The most efficient method would be to use reduce. Here I'm using array spread syntax to optionally add the index to the array used as the initial value of the accumulator.

var arr1 = [1,3,7,9,11];
var indexes = arr1.reduce((acc, cur, idx) => acc = cur > 7 ? [...acc, idx] : acc, []);
console.log(indexes);

Upvotes: 0

MattE
MattE

Reputation: 1114

You can do it like this:

    var arr1 = [2,4,8,10,12];
        
    console.log(arr1.filter(x => x>7).map(m => arr1.indexOf(m)))

returns [2, 3, 4]

Upvotes: 0

VLAZ
VLAZ

Reputation: 29088

You can Array#reduce and do this in one run of the array by checking and transforming the data at once

const arr1 = [1,3,7,9,11];

const result = arr1.reduce((acc, x, index) => acc.concat(x > 7 ? index : []), []);

console.log(result);

Upvotes: 2

Ian
Ian

Reputation: 6134

You can use map in combination with filter to achieve this:

arr1.map((x, i) => [x,i]).filter(([x,i]) => x > 7).map(([x,i]) => i);

This maps the array to an array of pairs where the first element is the original number and the second is the original index. Then it filters the pairs by the first element of each pair before mapping it back to the indexes.

Upvotes: 4

Related Questions