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
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.
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.
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 .
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.
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)
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With