Javascript 使用谓词-Typescript查找数组中的所有元素/索引

Javascript 使用谓词-Typescript查找数组中的所有元素/索引,javascript,angular,typescript,predicate,findall,Javascript,Angular,Typescript,Predicate,Findall,我想查找列表/数组中所有项目的索引,最好使用谓词 我使用离子角度框架,因此在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: myLi

我想查找列表/数组中所有项目的索引,最好使用谓词

我使用离子角度框架,因此在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;
    }
其他方法:

稍有不同,但可能有用(允许获取所有元素而不是索引):

PS:我选择从头到尾迭代循环,可以将循环反转为[2,3,6],而不是[6,3,2]


祝大家快乐

解决方案

    /**
     * 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;
    }
其他方法:

稍有不同,但可能有用(允许获取所有元素而不是索引):

PS:我选择从头到尾迭代循环,可以将循环反转为[2,3,6],而不是[6,3,2]

祝大家快乐

const myList = [0, 2, 1, 1, 3, 4, 1];
const allElements = myList.filter(x => x === 1);