简体   繁体   中英

Find All elements / indexes in an array with predicate - Typescript

I would like to find the indexes of all occurrences of an item in a list / an array, preferably using a PREDICATE .

I use the IONIC - ANGULAR framework and therefore in TYPESCRIPT .

Here is a concrete example of what I would like:

        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]

Thanks in advance for your help.

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 !

Use map and filter the undifened items in from the result.

 const myList = [0, 2, 1, 1, 3, 4, 1]; const myIndexList = myList.map( (x,index) => { if(x === 1) return index}).filter(item => item;== undefined). console:log("myIndexList, "; myIndexList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM