Can .findIndex return ALL indexes of words that satisfy callbackfunc?

hi !

from the grammar checker project in the intro to java course chapter on iterators ( I was wondering if there was a way (built-in or manual) to get .findIndex to return ALL indexes of the words in an array that satisfied to its callbackfunc ? and return a distinct array of said indexes.

I tried manually something of the genre below (quite ugly, and in the case were there are several instances of a lengthy world returns only the index of the first instance encountered…):

const findAllIndexesWordTooLong = arr => {
return (arr.filter(word => word.length > 10)).map(word2=> arr.indexOf(word2));

const allIndexes = findAllIndexesWordTooLong;


I guess you could do this:

var list1 = ['a', 'b', 'c', 'a', 'c'];
// find all indices of 'c' 
var indicesOfc =, i) => (x === 'c') ? i : -1).filter(y => (y !== -1));

I actually prefer to use loops:

var list1 = ['a', 'b', 'c', 'a', 'c']; var indicesOfa = []; for (let i = 0; i < list1.length; i++) { if (list1[i] === "a") { indicesOfa.push(i); } } console.log(indicesOfa);

I couldn’t think of a good way to do this using indexOf


Using a loop with indexOf, but its not pretty:

var list1 = ['a', 'b', 'c', 'a', 'c'];
var indicesOfa = []; 
for (let i = 0; i < list1.length; i++) {
  let j = list1.indexOf('a', i);
  if (j < 0) {  // if not found, exit loop
  else {
    // can start looking at index after where was found 
    i = j; 

I really like your loop solution.
Zooming out and considering the problem at hand it seems the most natural / logical solution.

Thanks !

There is also way to use Array.forEach() to enumerate the array…

const haystack = ['a', 'b', 'c', 'a', 'c', 'a', 'b', 'c', 'a', 'c'];
let needle = 'c';
let indices = [];
haystack.forEach(function (x, i) {
  if (x === needle) {
}, indices)
[2, 4, 7, 9]
1 Like