问题描述
我想找到的索引在列表/数组中的项的所有出现的,优选使用的 PREDICATE
我使用离子 - ANGULAR框架,因此在打字稿
下面是的,我想什么一个具体的例子:
const myList = [0,2,1,3,4,1];
// what already exists:
myList.findindex(x => x === 1); // return 2
// what I would like it to be:
myList.findAllIndexes(x => x === 1); // should return [2,6]
预先感谢您的帮助。
解决方法
解强>:
/**
* 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;
}
和使用它:
const myList = [0,2,1,3,4,1];
const indexes = this.findAllIndexes(myList,x => x === 1);
// return [6,2]
其他方法:强>
一个稍有不同,但可以是有用的(允许获取所有的元件,而索引):
const myList = [0,1];
const allElements = myList.filter(x => x === 1);
PS:我选择迭代从端部到开始循环时,有可能倒转以获得[2,3,6]代替[6,1,2]
。快乐作弄大家好!