I have an array of size 5010. For example, a=[0...5009] and my first element is placed at index 5002 which is dynamic and may change. So, how do I get directly the first element of the array without looping through array in javascript.
-
4What do you mean first element? The first element is at `a[0]` – nick zoum Jun 13 '19 at 13:14
-
Need more insights for What is first element – saketh Jun 13 '19 at 13:14
-
your first element is at index 0. if you want the item at 5002 use `myArray[5002]`... – I wrestled a bear once. Jun 13 '19 at 13:15
-
If you want to avoid writing a for loop, you can use `Array.filter()` for example. Which loops internally. Avoiding a loop at all isn't possible. Besides, I guess you are referring to your first element as a object with e.g id: 1 at position 5002 – r3dst0rm Jun 13 '19 at 13:15
-
1If your object has an unique id you may use the `.find` method. `arr.find( item => item.id === YOUR_ID )` – darklightcode Jun 13 '19 at 13:16
4 Answers
You need some kind of looping.
You could use Array#some
with a sparse array and return true
for the first nonsparsed item, after assigning the value to a variable.
This approach works for any value, even for undefined
or null
or any other falsy value.
var array = [],
index;
array.length = 5010;
array[5002] = null;
array.some((_, i) => (index = i, true));
console.log(index);
Array#findIndex
does not work with unknown value, because it visits every element, even the sparse elements.
var array = [],
index;
array.length = 5010;
array[5002] = 'some value'
index = array.findIndex((v, i) => (console.log(i, v), true));
console.log(index);

- 376,160
- 25
- 347
- 392
If the previous elements are undefined, you may need to filter the array first to get only defined values in the array.
const definedValues = array.filter(item => item); definedValues[0] // this will gives you the first defined item in the array.

- 38
- 7
If you want to get the index of an element whose value you already have, use Array#indexOf
.
var list = [1,2,3];
console.log(list.indexOf(2)); // 1
If you want to find the index using a function, use Array#findIndex
.
var list = [1,2,3];
console.log(list.findIndex(item => item === 2)); // 1
So if you want to find the first element that is a troothy do:
var list = [null,2,3];
console.log(list.findIndex(item => item)); // 1

- 7,216
- 7
- 36
- 80
You can try :
var array1 = [1, 2, 3];
var firstElement = array1.shift();
console.log(array1); // expected output: Array [2, 3]
console.log(firstElement); // expected output: 1
Here you can find some other examples Get first element in array