1
votes

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

5
I think one of those arr1 should be arr2. Given that, arr1.filter(x => arr2[x] > 7); - zero298
You can't do it with a .filter - the only thing .filter does is to reduce the amount of elements in the array, it doesn't transform them. You probably want reduce or a map to tuples (essentially tag values with their index) -> filter based on the data -> map back to indeces. - VLAZ
zeri298, yes you are correct, the second array is arr2, thanks - ket
filter accepts a special type of function called predicate. Return type of a predicate is Boolean by definition which limits filter functionality to just filter elements. - Xaqron

5 Answers

4
votes

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.

2
votes

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);
0
votes

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]

0
votes

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);
0
votes

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))