Javascript - Get Position Of The Element Of The Array
Solution 1:
consider using indexOf
, it returns the 0-based position of the element in the array.
e.g.
[1,2,3,4].indexOf(3); // produces 2
Note that this method is not available in IE 8 and below.
Solution 2:
jQuery provides yout with an "inArray" functionality, similar to PHP:
var a = [1,2,3,4];
console.log( jQuery.inArray(3, a) ); //returns 2
If you're already using jQuery in your project, this would be the way to go! jQuery uses indexOf (the fastest solution) if possible and steps back to a loop based solution if not.
Solution 3:
Or simple use a for loop:
functiongetPosition(elementToFind, arrayElements) {
var i;
for (i = 0; i < arrayElements.length; i += 1) {
if (arrayElements[i] === elementToFind) {
return i;
}
}
returnnull; //not found
}
getPosition(3, [1, 2, 3, 4]);
Solution 4:
As was already pointed out by some answers, arrays in newer browsers have methods like indexOf
map
and forEach
that are very convenient for avoiding writing lots of for-loops.
If you need to support old environments without these functions I would strongly recommend using a library (or writing one of your own) to implement those very common array operations (kind of how soc suggested).
var arrayfn = (function(){
var M = {};
M.indexOf = function(array, item){ ... };
M.contains = function(array, item){ return M.indefOf(array, item) !== -1; };
M.map = function(array, callback){ ... };
}());
arrayfn.contains([1,2,3], 2);
Most popular JS frameworks should already have most of these builtin anyway. Out of the top of my head I remember Dojo, jQuery and Underscore have some of these functions, for example.
Solution 5:
This example only demonstrate that is possible the use of map()
to return each element of the array. Once we have it, we retrieve the element's index in the array:
functionsearchPosition(elementToFind, array) {
returnarray.map(function(el) {
return el;
}).indexOf(elementToFind);
}
searchPosition(3, [1, 2, 3, 4]); // returns 2
BONUS:
This is not a part of the OP's question, but if you want to retrieve the position of the first element in the array that satisfies certain condition, you can do it with the findIndex()
function provided in the ES6:
vararray = [101, 90, 104, 80];
functionfindFirstLessNumber(element) {
return element < 100;
}
console.log(array.findIndex(findFirstLessNumber)); // returns 1 (the position of 90)
Post a Comment for "Javascript - Get Position Of The Element Of The Array"