Is there a way to get the index of the new array while filtering

I have a variable, idx, that controls the current index of an array of elements called items. While running a filter on this array, I want to change idx to current index of the filtered array if it matches a condition.

let idx = 5; //6 in the array
let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Filter evens only
let evens = items.filter(function(num) {
    if (!isEven(num))
        return false;
    if (num == 6)
        idx = INDEX_IN_EVENS_ARRAY(would be 2 in this case);
    return true;
});

1 thought on “Is there a way to get the index of the new array while filtering”

  1. Very simple solution using indexOf function.

    let idx = 5; //6 in the array
    let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    // Filter evens only
    let evens = items.filter(function(num) {
        return !(num % 2)
    })
    idx = evens.indexOf(6)
    
    console.log(evens)
    console.log(idx)
    Reply

Leave a Comment