-1

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.

Amala James
  • 1,336
  • 3
  • 16
  • 32
Neeraj
  • 57
  • 2
  • 9

4 Answers4

2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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.

0

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
nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

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

Clemsang
  • 5,053
  • 3
  • 23
  • 41
NikoSch
  • 1
  • 1