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]) {

}

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

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

?

3 Likes

Um, probably …