KoenDG
KoenDG

Reputation: 105

Find all indexes in an array that have a certain value

I'm working on a little something where figures are shown or hidden, based on what checkboxes on a list are checked or not.

To this end, I need to first collect an array of only the checkboxes that have been checked, so I can use their values for comparison with the list later on.

In order to do this, I wrote a little function, with the help of jQuery:

var findIndexesWithValue = function(arr, val) {
    //Find the correct indexes and put them in an array, for later use.
    var indexArray = [];

    $.grep(arr, function(elementOfArray, indexInArray) {
        //Get all indexes where the value corresponds
        if (arr[indexInArray] === val) {
            indexArray.push(indexInArray);
        }
    });

    return indexArray;
};

For those not familiar with $.grep: http://api.jquery.com/jQuery.grep/

My question is: am i re-inventing the wheel here? I made this because indexOf() returns only the first index at which a value is encountered and not all of them.

Upvotes: 1

Views: 1786

Answers (1)

charlietfl
charlietfl

Reputation: 171669

$.grep isn't really best jQuery array method for this situation.

$.map will work more effectively

var indexArray = $.map(arr, function(elementOfArray, indexInArray) {
        return elementOfArray == val ? indexInArray : null;
});


console.log( indexArray);

DEMO: http://jsfiddle.net/x8qgq/1/

Upvotes: 3

Related Questions