使用谓词查找数组中的所有元素/索引 - Typescript
Find All elements / indexes in an array with predicate - Typescript
我想找到列表/数组中某项所有出现的 indexes,最好使用 PREDICATE。
我使用 IONIC - ANGULAR 框架,因此在 TYPESCRIPT.
这是我想要的具体示例:
const myList = [0, 2, 1, 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, 3, 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, 1, 3, 4, 1];
const indexes = this.findAllIndexes(myList, x => x === 1);
// return [6, 3, 2]
其他方法:
有点不同但很有用(允许获取所有元素而不是索引):
const myList = [0, 2, 1, 1, 3, 4, 1];
const allElements = myList.filter(x => x === 1);
PS :我选择从头到尾迭代循环,可以将其反转得到 [2, 3, 6] 而不是 [6, 3, 2]。
祝大家编码愉快!
我想找到列表/数组中某项所有出现的 indexes,最好使用 PREDICATE。
我使用 IONIC - ANGULAR 框架,因此在 TYPESCRIPT.
这是我想要的具体示例:
const myList = [0, 2, 1, 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, 3, 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, 1, 3, 4, 1];
const indexes = this.findAllIndexes(myList, x => x === 1);
// return [6, 3, 2]
其他方法:
有点不同但很有用(允许获取所有元素而不是索引):
const myList = [0, 2, 1, 1, 3, 4, 1];
const allElements = myList.filter(x => x === 1);
PS :我选择从头到尾迭代循环,可以将其反转得到 [2, 3, 6] 而不是 [6, 3, 2]。
祝大家编码愉快!