Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element in array with index not starting from 0

I'm using a javascript library which returns arrays not starting from zero like starting from 26 or 1500, what i want to do is a method to get the first element in that array regardless of the index number starting with 0 or any other number.

Are they any method to do this in javascript ?

like image 673
azelix Avatar asked Jun 23 '16 11:06

azelix


People also ask

How do I return the first index of an array?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Is the first value of an array 0 or 1?

In computer science, array indices usually start at 0 in modern programming languages, so computer programmers might use zeroth in situations where others might use first, and so forth.

Why is the index of the first element in an array always zero?

In array, the index tells the distance from the starting element. So, the first element is at 0 distance from the starting element. So, that's why array start from 0.

How can we change the starting index of an array from 0 to 1?

Can we change the starting index of an array from 0 to 1 in any way? Explanation: No. You can not change the C Basic rules of Zero Starting Index of an Array.


1 Answers

I suggest to use Array#some. You get the first nonsparse element and the index. The iteration stops immediately if you return true in the callback:

var a = [, , 22, 33],
    value,
    index;

a.some(function (v, i) {
    value = v;
    index = i;
    return true;
});

console.log(index, value);
like image 182
Nina Scholz Avatar answered Nov 14 '22 22:11

Nina Scholz