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 (https://www.codecademy.com/courses/introduction-to-javascript/projects/mini-linter) 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;
console.log(allIndexes(storyWords));

thanks!

I guess you could do this:

var list1 = ['a', 'b', 'c', 'a', 'c'];
// find all indices of 'c' 
var indicesOfc = list1.map((x, 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

details

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
    break;
  }
  else {
    indicesOfa.push(j); 
    // can start looking at index after where was found 
    i = j; 
  }
}
console.log(indicesOfa);

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) {
    this.push(i)
  }
}, indices)
console.log(indices)
[2, 4, 7, 9]
1 Like