[javascript] How to get the first element of an array?

How do you get the first element from an array like this:

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];

I tried this:

alert($(ary).first());

But it would return [object Object]. So I need to get the first element from the array which should be the element 'first'.

This question is related to javascript arrays

The answer is


Using ES6.

let arr = [22,1,4,55,7,8,9,3,2,4];

let {0 : first ,[arr.length - 1] : last} = arr;
console.log(first, last);

or

let {0 : first ,length : l, [l - 1] : last} = [22,1,4,55,7,8,9,3,2,4];
console.log(first, last);

If you want to preserve the readibility you could always add a first function to the Array.protoype:

Array.prototype.first = function () {
    return this[0];
};

A then you could easily retrieve the first element:

[1, 2, 3].first();
> 1

Find the first element in an array using a filter:

In typescript:

function first<T>(arr: T[], filter: (v: T) => boolean): T {
    let result: T;
    return arr.some(v => { result = v; return filter(v); }) ? result : undefined;
}

In plain javascript:

function first(arr, filter) {
    var result;
    return arr.some(function (v) { result = v; return filter(v); }) ? result : undefined;
}

And similarly, indexOf:

In typescript:

function indexOf<T>(arr: T[], filter: (v: T) => boolean): number {
    let result: number;
    return arr.some((v, i) => { result = i; return filter(v); }) ? result : undefined;
}

In plain javascript:

function indexOf(arr, filter) {
    var result;
    return arr.some(function (v, i) { result = i; return filter(v); }) ? result : undefined;
}

The previous examples work well when the array index begins at zero. thomax's answer did not rely on the index starting at zero, but relied on Array.prototype.find to which I did not have access. The following solution using jQuery $.each worked well in my case.

let haystack = {100: 'first', 150: 'second'},
    found = null;

$.each(haystack, function( index, value ) {
    found = value;  // Save the first array element for later.
    return false;  // Immediately stop the $.each loop after the first array element.
});

console.log(found); // Prints 'first'.

You could also use .get(0):

alert($(ary).first().get(0));

To get the first element of the array.


_x000D_
_x000D_
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];_x000D_
alert(Object.values(ary)[0]);
_x000D_
_x000D_
_x000D_


You can do it by lodash _.head so easily.

_x000D_
_x000D_
var arr = ['first', 'second', 'third', 'fourth', 'fifth'];_x000D_
console.log(_.head(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


@thomax 's answer is pretty good, but will fail if the first element in the array is false or false-y (0, empty string, etc.). Better to just return true for anything other than undefined:

const arr = [];
arr[1] = '';
arr[2] = 'foo';

const first = arr.find((v) => { return (typeof v !== 'undefined'); });
console.log(first); // ''

If you're chaining a view functions to the array e.g.

array.map(i => i+1).filter(i => i > 3)

And want the first element after these functions you can simply add a .shift() it doesn't modify the original array, its a nicer way then array.map(i => i+1).filter(=> i > 3)[0]

If you want the first element of an array without modifying the original you can use array[0] or array.map(n=>n).shift() (without the map you will modify the original. In this case btw i would suggest the ..[0] version.


If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find():

var elements = []
elements[1] = 'foo'
elements[2] = 'bar'

var first = function(element) { return !!element }    
var gotcha = elements.find(first)

console.log(a[0]) // undefined
console.log(gotcha) // 'foo'

When there are multiple matches, JQuery's .first() is used for fetching the first DOM element that matched the css selector given to jquery.

You don't need jQuery to manipulate javascript arrays.


@NicoLwk You should remove elements with splice, that will shift your array back. So:

var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];

console.log(Object.keys(ary)[0]);

Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.


Just use ary.slice(0,1).pop();

In

_x000D_
_x000D_
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];_x000D_
_x000D_
console.log("1º "+ary.slice(0,1).pop());_x000D_
console.log("2º "+ary.slice(0,2).pop());_x000D_
console.log("3º "+ary.slice(0,3).pop());_x000D_
console.log("4º "+ary.slice(0,4).pop());_x000D_
console.log("5º "+ary.slice(0,5).pop());_x000D_
console.log("Last "+ary.slice(-1).pop());
_x000D_
_x000D_
_x000D_

array.slice(START,END).pop();


I know that people which come from other languages to JavaScript, looking for something like head() or first() to get the first element of an array, but how you can do that?

Imagine you have the array below:

const arr = [1, 2, 3, 4, 5];

In JavaScript, you can simply do:

const first = arr[0];

or a neater, newer way is:

const [first] = arr;

But you can also simply write a function like...

function first(arr) {
   if(!Array.isArray(arr)) return;
   return arr[0];
}

If using underscore, there are list of functions doing the same thing you looking for:

_.first 

_.head

_.take

Element of index 0 may not exist if the first element has been deleted:

_x000D_
_x000D_
let a = ['a', 'b', 'c'];_x000D_
delete a[0];_x000D_
_x000D_
for (let i in a) {_x000D_
  console.log(i + ' ' + a[i]);_x000D_
}
_x000D_
_x000D_
_x000D_

Better way to get the first element without jQuery:

_x000D_
_x000D_
function first(p) {_x000D_
  for (let i in p) return p[i];_x000D_
}_x000D_
_x000D_
console.log( first(['a', 'b', 'c']) );
_x000D_
_x000D_
_x000D_


array.find(e => !!e);  // return the first element 

since "find" return the first element that matches the filter && !!e match any element.

Note This works only when the first element is not a "Falsy" : null, false, NaN, "", 0, undefined


Some of ways below for different circumstances.

In most normal cases, the simplest way to access the first element is by

yourArray[0]

but this requires you to check if [0] actually exists.

There are real world cases where you don't care about the original array, and don't want to check if index exists, you want just to get the first element or undefined inline.

In this case, you can use shift() method to get the first element, but be cautious that this method modifies the original array (removes the first item and returns it). Therefore the length of an array is reduced by one. This method can be used in inline cases where you just need to get the first element, but you dont care about the original array.

yourArray.shift()

The important thing to know is that the two above are only an option if your array starts with a [0] index.

There are cases where the first element has been deleted, example with, delete yourArray[0] leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.

So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.

You can use find() to get the first element.

The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below). (You can customize the condition to exclude null or other empty values too)

var firstItem = yourArray.find(x=>x!==undefined);

I'd also like to include filter() here as an option to first "fix" the array in the copy and then get the first element while keeping the the original array intact (unmodified).

Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).

var firstItem = yourArray.filter(x => typeof x!==undefined).shift();

Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach, for example.

(I see some people suggest using for...in loop to get the first element, but I would recommend against this method for...in should not be used to iterate over an Array where the index order is important because it doesn't guarantee the order although you can argue browsers mostly respect the order.By the way, forEach doesn't solve the issue as many suggest because you cant break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value

Both find() and filter() guarantee the order of elements, so are safe to use as above.


Another one for those only concerned with truthy elements

ary.find(Boolean);

Why not account for times your array might be empty?

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
first = (array) => array.length ? array[0] : 'no items';
first(ary)
// output: first

var ary = [];
first(ary)
// output: no items

Only in case you are using underscore.js (http://underscorejs.org/) you can do:

_.first(your_array);

Why are you jQuery-ifying a vanilla JavaScript array? Use standard JavaScript!

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Also, needs more jQuery

Source, courtesy of bobince


Using ES6 destructuring

let [first] = [1,2,3];

Which is the same as

let first = [1,2,3][0];

Use this to split character in javascript.

var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");

In ES2015 and above, using array destructuring:

_x000D_
_x000D_
const arr = [42, 555, 666, 777]_x000D_
const [first] = arr_x000D_
console.log(first)
_x000D_
_x000D_
_x000D_


ES6 easy:

let a = []
a[7] = 'A'
a[10] = 'B'

let firstValue = a.find(v => v)
let firstIndex = a.findIndex(v => v)

You can use the combination of reverse then pop. The idea is to reverse the array then pop which will get you the last item in that array.

Be careful as this will modify the original array.

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];_x000D_
var first = fruits.reverse().pop();_x000D_
  _x000D_
console.log('First element -->', first);_x000D_
console.log('Original array -->', fruits);
_x000D_
_x000D_
_x000D_


Try alert(ary[0]);.


Declare a prototype to get first array element as:

Array.prototype.first = function () {
   return this[0];
};

Then use it as:

var array = [0, 1, 2, 3];
var first = array.first();
var _first = [0, 1, 2, 3].first();

Or simply (:

first = array[0];

You can just use find():

let first = array.find(Boolean);

Or if you want the first element even if it is falsy:

let first = array.find(e => true);

Going the extra mile:

If you care about readability but don't want to rely on numeric incidences you could add a first()-function to Array.protoype by defining it with Object?.define?Property() which mitigates the pitfalls of modifying the built-in Array object prototype directly (explained here).

Performance is pretty good (find() stops after the first element) but it isn't perfect or universally accessible (ES6 only). For more background read @Selays answer.

Object.defineProperty(Array.prototype, 'first', {
  value() {
    return this.find(e => true);     // or this.find(Boolean)
  }
});

Then to retrieve the first element you can do:

let array = ['a', 'b', 'c'];
array.first();

> 'a'

Snippet to see it in action:

_x000D_
_x000D_
Object.defineProperty(Array.prototype, 'first', {_x000D_
  value() {_x000D_
    return this.find(Boolean);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log( ['a', 'b', 'c'].first() );
_x000D_
_x000D_
_x000D_


ES6 Spread operator + .shift() solution

Using myArray.shift() you can get the 1st element of the array, but .shift() will modify the original array, so to avoid this, first you can create a copy of the array with [...myArray] and then apply the .shift() to this copy:

_x000D_
_x000D_
var myArray = ['first', 'second', 'third', 'fourth', 'fifth'];

var first = [...myArray].shift();        

console.log(first);
_x000D_
_x000D_
_x000D_


Method that works with arrays, and it works with objects too (beware, objects don't have a guaranteed order!).

I prefer this method the most, because original array is not modified.

// In case of array
var arr = [];
arr[3] = 'first';
arr[7] = 'last';
var firstElement;
for(var i in arr){
    firstElement = arr[i];
    break;
}
console.log(firstElement);  // "first"

// In case of object
var obj = {
    first: 'first',
    last: 'last',
};

var firstElement;

for(var i in obj){
    firstElement = obj[i];
    break;
}

console.log(firstElement) // First;