Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for multiple index(es) of same values in javascript array

I have a 1 dimensional array like:

var abc = ['a','a','b','a','c']

Now I want to get back all the indexes of 'a', that is 0, 1 and 3.

Are there any simple solutions?

P.S.

I know IndexOf or jQuery.inArray(). But they just returned the index of first matched element only

like image 322
Capitaine Avatar asked Jun 16 '14 10:06

Capitaine


People also ask

How do you select multiple indexes in an array?

The trick is to call the map function on an array of the desired indexes. An array map function will return an array of the same length as the array it is called on. The callback function inside the map function ( x=>my_array[x] ) then returns the value of my_array for each of the desired indexes.

How do you find the index of the same element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do you search multiple elements in an array?

To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .

How do you find the index where a number belongs in an array in JavaScript?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

You could extend the basic Array Object with the following method:

Array.prototype.multiIndexOf = function (el) { 
    var idxs = [];
    for (var i = this.length - 1; i >= 0; i--) {
        if (this[i] === el) {
            idxs.unshift(i);
        }
    }
    return idxs;
};

Then the operation

var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');

would give you the result:

[0, 1, 3]

Jsperf comparison of unshift / push / push(reverse order)

like image 63
Matyas Avatar answered Oct 05 '22 12:10

Matyas


You can take advantage of the fact that $.map() does not push values in its resulting array when the function you pass returns undefined.

Therefore, you can write:

var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
    if (element == "a") {
        return index;
    }
});
like image 43
Frédéric Hamidi Avatar answered Oct 05 '22 12:10

Frédéric Hamidi