How to get value at a specific index of array In JavaScript?
JavascriptJavascript Problem Overview
I have an array and simply want to get the element at index 1.
var myValues = new Array();
var valueAtIndex1 = myValues.getValue(1); // (something like this)
How can I get the value at the 1st index of my array in JavaScript?
Javascript Solutions
Solution 1 - Javascript
Just use indexer
var valueAtIndex1 = myValues[1];
Update from Chrome 92 (released on: July 2021)
You can use at
method from Array.prototype
as follows:
var valueAtIndex1 = myValues.at(1);
See more details at MDN documentation.
Solution 2 - Javascript
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
Solution 3 - Javascript
You can just use []
:
var valueAtIndex1 = myValues[1];
Solution 4 - Javascript
indexer (array[index]
) is the most frequent use. An alternative is at
array method:
const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'
If you come from another programming language, maybe it looks more familiar.
Solution 5 - Javascript
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
Solution 6 - Javascript
You can use [];
var indexValue = Index[1];
Solution 7 - Javascript
Update 2022
With ES2022 you can use Array.prototype.at()
:
const myValues = [1, 2, 3]
myValues.at(1) // 2
at()
also supports negative index, which returns an element from the end of the array:
const myValues = [1, 2, 3]
myValues.at(-1) // 3
myValues.at(-2) // 2
Read more: MDN, JavascriptTutorial, Specifications