DEV Community

SerialEditor
SerialEditor

Posted on

I lack a built-in method

JS contains a filter method that returns an array of search items. I would very much like to have a similar method that returns an array of indices of suitable elements. I know the findIndex method, but it only returns the first suitable index, while it would be nice to get all the necessary indices in one row.
This post is published as my personal wish.

Top comments (2)

Collapse
 
h_sifat profile image
Muhammad Sifat Hossain • Edited

Hi there, welcome to Dev. Please know that Dev is not a QA site. It's better to ask your questions on QA focused site like StackOverflow. Nevertheless, I'll answer your question. You don't need another builtin array method to solve your problem.

function filterIndices(array, predicate) {
  const filtered = [];

  for (let i = 0; i < array.length; i++) {
    const isValid = predicate(array[i], i, array);
    if (isValid) filtered.push(i);
  }

  return filtered;
}

const array = ["a", "c", "x", "y", "e"];
const filtered_indices = filterIndices(array, (c) => c < "f");
console.log(filtered_indices); // [ 0, 1, 4 ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sethcalebweeks profile image
Caleb Weeks

Welcome to dev.to! Out of curiosity, what is the use case for wanting the indices instead of the items themselves? Reduce might be your best bet:

const filterIndices = (arr, predicate) => arr.reduce(
    (filtered_indices, item, i) => {
        if (predicate(item)) {
            filtered_indices.push(i)
        }
        return filtered_indices
    },
[])
Enter fullscreen mode Exit fullscreen mode