422

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'.

Henke
  • 4,445
  • 3
  • 31
  • 44
MacMac
  • 34,294
  • 55
  • 151
  • 222

37 Answers37

515

like this

alert(ary[0])
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • 136
    This assumes that the first element in the array is always has an index of 0. You know what they say about assumption... – Andy Aug 09 '15 at 16:19
246

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

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
202

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.

Another commonly used method is shift() but you should avoid using this for the purpose of accessing the first element.

Well, this method modifies the original array (removes the first item and returns it) but re-indexes what is left in the array to make it start from 0 (shifts everything down). Therefore the length of an array is reduced by one. There are good cases where you may need this, for example, to take the first customer waiting in the queue, but it is very inefficient to use this for the purpose of accessing the first element.

In addition, this requires a perfect array with [0] index pointer intact, exactly as using [0];

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, for 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 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.

Another one I have seen in some projects is splice() to get the first item in an array and then get it by index:

var firstItem = yourArray.splice(0, 1)[0];

I am not sure why you would do that. This method won't solve the problem with holes in an array (sparse array). It is costly as it will re-index the array, and it returns an array that you have to access again to get the value. For example, if you delete the first couple of elements, then splice() will return undefined instead of the first defined value from the array.

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

**(I see some people suggest using loops to get the first element, but I would recommend against this method. Obviously, you can use any loop to get a value from an array but why would you do that? Readability, optimization, unnecessary block of code etc. When using native functions, the browser can better optimize your code. And it may not even work with some loops which don't guarantee the order in iteration.

By the way, forEach() doesn't solve the issue as many suggest because you can't break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value, but why?**

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Selay
  • 6,024
  • 2
  • 27
  • 23
136

Using ES6 destructuring

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

Which is the same as

let first = [1,2,3][0];
Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
127

You can just use find():

const first = array.find(Boolean)

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

const first = array.find(() => true)

Or if you want the first element even if it is falsy but not if it is null or undefined (more information):

const first = array.find(e => typeof e !== 'undefined')



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.prototype 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)
  }
})

To retrieve the first element you are now able to do this:

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

> 'a'

Snippet to see it in action:

Object.defineProperty(Array.prototype, 'first', {
  value() {
    return this.find(Boolean)
  }
})

console.log( ['a', 'b', 'c'].first() )
leonheess
  • 16,068
  • 14
  • 77
  • 112
63

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

let a = ['a', 'b', 'c'];
delete a[0];

for (let i in a) {
  console.log(i + ' ' + a[i]);
}

Better way to get the first element without jQuery:

function first(p) {
  for (let i in p) return p[i];
}

console.log( first(['a', 'b', 'c']) );
leonheess
  • 16,068
  • 14
  • 77
  • 112
NicoLwk
  • 631
  • 5
  • 2
45

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
eliocs
  • 18,511
  • 7
  • 40
  • 52
20

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'
thomax
  • 9,213
  • 3
  • 49
  • 68
  • Won't work in IE11: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – Corey Alix Mar 13 '17 at 12:56
  • 1
    I'd advise against using `!!element` as it'll skip falsy values. I'd recommend using `find()` in this manner: `sparse.find((_, index, array) => index in array);` – Victor Welling Jul 27 '18 at 08:58
  • Similar approach without dismissing falsy values here: https://stackoverflow.com/a/56115413/7910454 – leonheess May 14 '19 at 09:22
19
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

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 4
    this is great and also works great in TypeScript. What about simplifying to `array.find(() => true);`? This allows you to do `[false].find(() => true)` as well. – Simon Warta Jul 04 '18 at 21:11
  • @SimonWarta of course `.find(value => true)` is just working as expected… but honestly if you want a cleaner code and to keep the typing in typescript, use the [destructuring](http://www.typescriptlang.org/play/#src=const%20%5Bfirst%2C%20second%5D%20%3D%20%5B'first'%2C%202%5D%3B%0D%0A%2F%2F%20fails%20because%20typescript%20understands%20the%20types%20of%20the%20array%20items%0D%0Afirst%20%3D%3D%3D%20second%3B). – Flavien Volken Oct 15 '18 at 05:50
16

In ES2015 and above, using array destructuring:

const arr = [42, 555, 666, 777]
const [first] = arr
console.log(first)
Vik
  • 3,495
  • 3
  • 22
  • 25
12

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
Alireza
  • 100,211
  • 27
  • 269
  • 172
12

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:

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

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

console.log(first);
Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56
نور
  • 1,425
  • 2
  • 22
  • 38
11

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

_.first(your_array);
pastullo
  • 4,171
  • 3
  • 30
  • 36
9

Try alert(ary[0]);.

thejh
  • 44,854
  • 16
  • 96
  • 107
8

I prefer to use Array Destructuring

const [first, second, third] = ["Laide", "Gabriel", "Jets"];
console.log(first);  // Output: Laide
console.log(second); // Output: Gabriel
console.log(third);  // Output: Jets
Vitor Teofilo
  • 91
  • 2
  • 1
7

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;
Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
7

Another one for those only concerned with truthy elements

ary.find(Boolean);
Vinnie
  • 1,670
  • 14
  • 16
6

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;
}
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
Corey Alix
  • 2,694
  • 2
  • 27
  • 38
6

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

In

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

console.log("1º "+ary.slice(0,1).pop());
console.log("2º "+ary.slice(0,2).pop());
console.log("3º "+ary.slice(0,3).pop());
console.log("4º "+ary.slice(0,4).pop());
console.log("5º "+ary.slice(0,5).pop());
console.log("Last "+ary.slice(-1).pop());

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

Guilherme HS
  • 164
  • 1
  • 6
4

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
NathanQ
  • 1,024
  • 18
  • 20
3

You could also use .get(0):

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

To get the first element of the array.

3

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.

letronje
  • 9,002
  • 9
  • 45
  • 53
3

A vanilla JS code, no jQuery, no libs, no-nothing.. :P.. It will work if array index does not start at zero as well.

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.values(ary)[0]);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Merak Marey
  • 749
  • 5
  • 15
2

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];
ozhanli
  • 1,456
  • 18
  • 25
2

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'.
Matthew
  • 309
  • 4
  • 12
1

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.

Michael J. Zoidl
  • 1,708
  • 16
  • 13
1
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.

Anuga
  • 2,619
  • 1
  • 18
  • 27
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – DimaSan Feb 27 '17 at 17:37
1

try

var array= ['first', 'second', 'third', 'fourth', 'fifth'];
firstElement = array[array.length - array.length];

https://playcode.io/908187

Promo IL
  • 167
  • 1
  • 8
1
var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first
cosnole.log(ary);
// ["second", "third", "fourth", "fifth"]
bardala
  • 51
  • 7
  • 2
    For answers that cause side-effects, please note them in the answer. In this case, the array is modified. – General Grievance Aug 30 '22 at 02:16
  • 1
    Please also check other answers before posting. This answer has [already been provided](https://stackoverflow.com/a/27180125/5648954). – Nick Parsons Sep 12 '22 at 11:39
  • This will work fine, but mutating values can easily cause bugs. A slightly safer option could be to clone `ary` so it doesn't mutate: `[...ary].shift()` – Andre OBrien Nov 07 '22 at 23:30
1

The issue with the other answers is that many won't handle cases where the array is empty or undefined, and the ones that do handle this are either hard to read or require using a library.

The cleanest pure JavaScript way I can think to handle this is by using optional chaining and a ternary operator:

const first = array?.length ? array[0] : undefined

You can also do this without optional chaining if you need to support older browsers:

const first = array && array.length ? array[0] : undefined

The other advantage of this is that if you need to return a value other than undefined (eg returning null in a React component) you easily update the code to do this.

Andre OBrien
  • 160
  • 1
  • 11
0

@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]);}
asinino
  • 29
  • 1
0

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);
Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49
0

The slice(start,end) method returns a shallow copy of a part of an array into a new array object selected from start to end position:

  const numbers = ['first', 'second', 'third', 'fourth', 'fifth']
  const selectedNum = numbers.slice(0, 1)[0]
  console.log(selectedNum) // "first"
fbarikzehy
  • 4,885
  • 2
  • 33
  • 39
0

Simple way to get first value of an array

const dummyArray = [1,2,3,4,5]
console.log(dummyArray[0]) // 1

You can use array de-structure to get first value

const dummyArray = [1,2,3,4,5]
const [fisrt ,...remaining] = dummyArray
console.log(fisrt) // 1
console.log(remaining) //[2,3,4,5]

If You want to create a function that will return first value of array index.

const fisrtElement = (arr) => {
if(Array.isArray && Array.isArray(arr) ) {
    return arr[0] || 0
  }
  return 0
}

const first = fisrtElement(dummyArray);
-1

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(",");
Mohit Singh
  • 5,977
  • 2
  • 24
  • 25
-1

@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); // ''
derikb
  • 59
  • 1
  • 7
-1

ES6 easy:

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

let firstValue = a.find(v => v)
let firstIndex = a.findIndex(v => v)
Jan Jarčík
  • 2,681
  • 2
  • 18
  • 21
  • 1
    Nope… it will return the first defined value. If the first one is null, undefined, false, 0 or an empty string, that one will be skipped. Try: ```[false, 0, null, undefined, '', 'last'].find(v => v)``` – Flavien Volken May 09 '18 at 08:20
  • Good point, my solution works only for array with defined values. – Jan Jarčík May 10 '18 at 11:30
  • 1
    Then why to filter using the value? `a.find(value => true)` won't dismiss any values. Still, I do not recommend using find to get the first item. – Flavien Volken Oct 15 '18 at 05:55
  • @FlavienVolken I used something similar in [my answer](https://stackoverflow.com/a/56115413/7910454). Why would you not recommend using it? – leonheess May 14 '19 at 07:49
  • 1
    @MiXT4PE returning true (as in your answer) is okay because it will stop at the first element, here it returns the element itself… which will continue if that one is considered false – Flavien Volken May 14 '19 at 08:49
  • @FlavienVolken Thanks for the fast response but I was talking about using `find()` in general because you wrote: *Still, I do not recommend using find to get the first item.* – leonheess May 14 '19 at 09:19
  • 1
    @MiXT4PE using "find" is slower, more complicated and less elegant. I also doubt there is any smart editor able to refactor this operation. Using destructuring is much more efficient, understood by the language (so you can refactor), the type is understood by the compiler (in case of TS), and very likely the fastest solution. – Flavien Volken May 14 '19 at 16:20