SOLUTION :
/**
* Returns the indexes of all elements in the array where predicate is true, [] otherwise.
* @param array The source array to search in
* @param predicate find calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* it is added to indexes and the functions continue..
*/
findAllIndexes<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number[] {
const indexes = [];
let l = array.length;
while (l--) {
if (predicate(array[l], l, array)) {
indexes.push(l);
}
}
return indexes;
}
and to use it :
const myList = [0, 2, 1, 1, 3, 4, 1];
const indexes = this.findAllIndexes(myList, x => x === 1);
// return [6, 3, 2]
OTHER METHOD :
A little different but can be useful (allow to get all elements and not indexes) :
const myList = [0, 2, 1, 1, 3, 4, 1];
const allElements = myList.filter(x => x === 1);
PS : I chose to iterate the loop from the end to the beginning, it is possible to invert it to get [2, 3, 6] instead of [6, 3, 2].
Happy codding everyone !
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…