Array.prototype.findAllIndices - for Array.prototype.findIndex

Situation

Different from Sets, array values don't have to be unique, so finding the index of a given value returns only one of n possible indecies. That's not wrong but misleading. And as we can see on mdn with Array.prototype.indexOf the workaround is a little messy:

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

Array.prototype.findAll(searchValue) on the other hand is essentially Array.prototype.filter((value) => value === searchValue)

Similar pairs

  • String.prototype.match() and String.prototype.matchAll()

Similar proposals

Aliases

  • Array.prototype.findAllIndexes()
  • Array.prototype.findIndexAll()

Method signature:

Same as Array.prototype.findIndex() except for the return type

/**
 * @param {(callback(element[, index[, array]]) => bool} callback
 * @return int[] - array of indices
 */
Array.prototype.findAllIndices = function(callback(element[, index[, array]])[, thisArg]) {

}
1 Like

“find” always returns a single thing; it seems like you want “filterIndexes” or similar, as sugar for:

arr.flatMap((x, i) => predicate(x) ? i : [])

?

5 Likes

Um, probably …

I think names like findIndices and filterIndices are more consistent with current naming conventions.

We could also have a findEntry, findLastEntry, and findEntries, which do the same as find, findLast, and filter (respectively), but return an index paired with its corresponding value (as a length=2 Array).

Names inspired by Object.entries