Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...