Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get position of the element of the array

Tags:

For instance, a variable named arrayElements of array type contains [1,2,3,4].

How do i get the position of which that has the value "3" in the array variable besides using loop?

thanks.

like image 519
Jia-Luo Avatar asked Jan 14 '12 16:01

Jia-Luo


People also ask

What is index position in JavaScript?

Definition and Usage. The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.

How do I get the last index of an array?

lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .

What is the difference between findIndex and indexOf?

findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise. indexOf - Returns the index of the first occurrence of a value in an array.


2 Answers

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.

like image 110
qiao Avatar answered Sep 22 '22 15:09

qiao


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.

like image 29
zaphod1984 Avatar answered Sep 23 '22 15:09

zaphod1984