Search code examples
javascriptangulartypescriptpredicatefindall

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

  • 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 !