368

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
  • 2,831
  • 2
  • 16
  • 26
MacMac
  • 32,380
  • 54
  • 146
  • 219

33 Answers33

476

like this

alert(ary[0])
John Hartsock
  • 82,242
  • 22
  • 125
  • 144
  • 45
    `var a = []; a[7] = 'foo'; alert(a[0]);` – Petah Jun 16 '15 at 00:41
  • 101
    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
  • 21
    @Andy There were no assumptions, as OP's question was quite clear and specific. – John Hartsock Aug 11 '15 at 00:36
  • 7
    @Petah there's nothing wrong with that code. It simply shows undefined, since that's the value of a[0], which actually is the first item in the array. If you want it to show foo you should skip all undefined values but it wouldn't be the first item in the array. – Michiel van der Blonk Sep 06 '16 at 10:37
  • 5
    @MichielvanderBlonk I was simply pointing out an edge case that some users might not expect. – Petah Sep 06 '16 at 20:14
  • 2
    @Petah: `var a = []; a[7] = 'foo'; alert(a[Object.keys(a)[0]]);` – Antonio Oct 23 '17 at 22:21
  • 4
    @JohnHartsock what if the array is empty and there is no [0] value ? does this code cause an error ? – Terai Jun 08 '18 at 09:35
  • 1
    Why was this answer so upvoted despite the comments here stating it's not always right? [NicoLwk's answer](https://stackoverflow.com/a/11506725/1128918) is probably not the best solution but at least is fail-proof for arrays without a `0` index. – Gustavo Straube Aug 15 '18 at 12:20
  • @GustavoStraube arrays always have a `0` index. If you do `delete a[0]` or do not set the `0` index, `a[0]` will return `undefined` which is right. You should either use `shift()`/`splice()` or make your own function to skip `undefined` indexes. – Pierre C. Dec 14 '18 at 10:37
  • @PierreC. Undefined stands for not defined. According to your proposition, I can say arrays always have any index. `a[49238]` will also return `undefined` if I delete it or never set that specific index. In any way, nothing of this makes this answer correct. – Gustavo Straube Dec 14 '18 at 14:00
  • 1
    @GustavoStraube I guess it depends on how you understand the question. That is how JavaScript works and the OP did not specify he wanted the first **defined** element. In my view this answer makes less assumptions than the one you linked. – Pierre C. Dec 14 '18 at 14:31
  • I feel so dumb for searching this up - the answer was so obvious! Thanks mate! – Nanoo Jun 12 '20 at 18:23
  • I mean this does directly answer the specifics of the question, but Stack Overflow is more than that. This answer literally only answers "get the first element of an array when its index is zero". No downvote but would have been nice to have given a bit more love to some circumstances and a few scenarios – James Apr 07 '21 at 17:13
  • @GustavoStraube Well it seems (*at the current moment*) that 469 of your peers and the OP disagree with you. Arrays always have an index `0`. Whether or not there's a defined value there is irrelevant to the question posed by OP. OP provided an example array even. It's not our part to change and answer a different question simply because we disagree with other answers. – Drew Reese Oct 01 '21 at 18:24
  • @DrewReese You're right. To be honest, I don't even know why I stated that 3 yrs ago in the first place. I know items in an array are moved "to the left" when an item at a lower index is deleted. Please disregard what I said before. I won't delete the comments only to keep the context. – Gustavo Straube Oct 04 '21 at 18:02
242

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
  • 344,413
  • 96
  • 627
  • 693
164

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.

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

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 array (sparse array). It is costly as it will re-index the array, and it returns an array and you have to access again to get the value. For example, if you delete first couple of elements and splice will return undefined instead of the first defined value from array.

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

Selay
  • 5,266
  • 2
  • 26
  • 22
  • 1
    Why not just unshift the array afterwards, e.g.: var element = yourArray.shift(); yourArray.unshift(element); – Greg May 31 '16 at 19:11
  • 11
    Because it is very inefficient and bad thing. You can get the first element in a much efficient way. Both shift and unshift do some checks and traverse the entire array to achieve the task because when you remove or add a new element to the beginning, all other indexes should be shifted. It is like you have a bus full of people, and when somebody from the rear seat wants to get off, you empty the bus through the front door and then ask them get on again. – Selay Jul 26 '16 at 00:13
  • 1
    @Selay that depends on the specific internals of the interpreter. – Michiel van der Blonk Sep 06 '16 at 10:46
  • @Michiel van der Blonk Can you please let me know which interpreter does it as you mentioned. I am very interested. All of the implementations known to me uses loop and copy. It is how JavaScript arrays work. You can't simply remove the first element easily because the remaining array now starts from 1 (element at position 0 removed), which you need to fix. You can't make magic no matter what internal implementation you have. – Selay Dec 18 '16 at 11:58
  • If you use `yourArray.map(n=>n).shift()` it will return the first item without modifying the original... don't know if it's the best way but if you chain a array with .map().filter().some().shift() it's okay.. otherwise i would use `yourArray[0]` – Michael J. Zoidl Feb 01 '17 at 08:22
  • @Selay I'm sorry I don't know. Perhaps at one point I knew, but I can't remember. – Michiel van der Blonk Mar 07 '17 at 16:13
  • "requires you to check if [0] actually exists" - it doesn't `let arr = [];` both: ` arr[0]` and `arr.shift()` returns `undefined` if you don't care about the array after all, both would be fine – eudaimonia Mar 30 '22 at 16:20
  • Yes, thats right. I have in bold there that this is only an option if your array starts with [0]. If your array is sparse, simple accessors such as [0], shift, splice etc won't work. – Selay Apr 14 '22 at 07:38
106

Using ES6 destructuring

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

Which is the same as

let first = [1,2,3][0];
Flavien Volken
  • 16,172
  • 11
  • 86
  • 115
  • It might be relevant to add that Destructing is only an option if your array starts with a [0] index. – leonheess May 16 '19 at 07:04
  • 3
    @leonheess All JavaScript arrays start at `[0]` index. – Jonathan Nov 18 '20 at 14:41
  • @Jonathan That depends on how you define starting. I can create an array like this `[,'a','b','c']`. I'd argue it starts at index 1. – leonheess Nov 18 '20 at 15:26
  • @leonheess I guess? To me that array still starts at `0`, but you inserted an `undefined` value. ‍♂️ – Jonathan Nov 18 '20 at 16:04
  • @Jonathan Well, getting index `[-1]` also returns undefined – leonheess Nov 18 '20 at 16:47
  • @leonheess as would `{}['anyUndefinedKey']` do. You can however have a "sparse array like" using `var sparse = Array(42)` but this is still an object of type "Array" with no values in it…. And beginning with an index `[0]` https://www.oreilly.com/library/view/javascript-the-definitive/9781449393854/ch07s03.html#:~:text=A%20sparse%20array%20is%20one,than%20the%20number%20of%20elements. – Flavien Volken Nov 18 '20 at 17:13
  • @FlavienVolken I agree! That's why I wrote [this answer](https://stackoverflow.com/a/56115413/7910454) to get the actual first element and not the one at index 0 (: – leonheess Nov 18 '20 at 22:09
  • in the fine prints I disagree with your solution, because you might store `undefined` on purpose within your sparse array. If you really want to get the first item you stored by your own, then you should use `anArray[Object.getOwnPropertyNames(anArray)[0]]` but honestly I never had to use this :-) and I hope I won't ever. I am not sure neither the property names orders are cross browser compliant. They should normally be ascending positive index first (including zero) then the regular properties name (length, negative values, keys) – Flavien Volken Nov 19 '20 at 13:40
  • @leonheess : "All JavaScript arrays start at [0] index". Not true. An array can be constructed with specific ID's starting at something else than 0. – Christian Bonato Dec 07 '21 at 13:05
  • 1
    @ChristianBonato I think you mistagged me or misread my comments. I agree with you. The quoted text is from Jonathan's comment Btw: With [my solution](https://stackoverflow.com/a/56115413/7910454) you get the first element regardless of where your array starts. – leonheess Dec 07 '21 at 14:13
  • @leonheess — Whoops! Sorry about that! @Jonathan (and its wrongly upvoted comment) was indeed the rant's target. `array.find(e => !!e);` is indeed the right solution (assuming the array contains non faulty entries). – Christian Bonato Dec 07 '21 at 19:30
93

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
  • 10,362
  • 9
  • 56
  • 89
  • And what happens if in a future version of the language they will add find() ? :-) wouldn't the above snippet break it ? – Bogdan Sep 09 '19 at 17:50
  • @Bogdan What do you mean *when they will add `find()`*? [`find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) has long been part of the language. It is the reason why the above snippet works. – leonheess Sep 09 '19 at 20:41
  • Ohh. Sorry bit tired haven't slept much i was referring to first. – Bogdan Sep 09 '19 at 21:20
  • @Bogdan It would still work perfectly fine but overwrite the potential future `first()`-method of the language – leonheess Sep 11 '19 at 08:23
59

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
  • 10,362
  • 9
  • 56
  • 89
NicoLwk
  • 591
  • 4
  • 2
44

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
  • 17,863
  • 7
  • 38
  • 50
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
  • 8,465
  • 3
  • 45
  • 66
  • 3
    This should really be voted higher. It's the most concise solution I see that uses vanilla js and accounts for sparse arrays. – Dominic P Feb 01 '17 at 08:10
  • 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
17
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
  • 76,783
  • 33
  • 229
  • 231
  • 1
    Abdennour to clarify for others your condition matchs any truthy element, i.e. const example = [null, NaN, 0, undefined, {}, 3, 'a']; const firstTruthyElement = example.find(e => !!e); // assigns the 5th element, the first non falsy: {} – PDA Sep 19 '17 at 15:39
  • Thanks @PDA for the catch up . BTW, empty string is considered also falsy – Abdennour TOUMI Sep 19 '17 at 16:17
  • 3
    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
  • See [this answer](https://stackoverflow.com/a/56115413/7910454) for a similar way without the pitfalls of ignoring falsy elements – leonheess Jul 25 '19 at 13:05
12

In ES2015 and above, using array destructuring:

const arr = [42, 555, 666, 777]
const [first] = arr
console.log(first)
Vik
  • 3,255
  • 3
  • 19
  • 25
11

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

_.first(your_array);
pastullo
  • 4,101
  • 2
  • 28
  • 36
10

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
  • 93,149
  • 25
  • 259
  • 162
9

Try alert(ary[0]);.

thejh
  • 43,352
  • 16
  • 93
  • 105
8

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
  • 12,842
  • 6
  • 48
  • 46
نور
  • 1,196
  • 2
  • 15
  • 34
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
  • 16,985
  • 5
  • 53
  • 74
7

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
  • 81
  • 2
  • 1
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
  • 23,917
  • 16
  • 136
  • 163
Corey Alix
  • 2,577
  • 2
  • 24
  • 36
6

Another one for those only concerned with truthy elements

ary.find(Boolean);
Vinnie
  • 1,570
  • 13
  • 15
5

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
  • 154
  • 1
  • 6
  • Why this and not `ary[0]`? – nathanfranke May 24 '20 at 04:03
  • @nathanfranke Because the question is a pretty ***generic*** "How to get the first element of an array?" and there are already several highly upvoted answers using `ary[0]` so this would be a duplicate if answered as you suggest. Using slice/pop also makes grabbing the last element trivial, i.e. `const last = ary.slice(-1).pop()`. – Drew Reese Oct 01 '21 at 16:59
  • Is there an example of how duplicating the array and `pop`-ing is better in some way for getting the first element of an array? – nathanfranke Dec 06 '21 at 16:52
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,004
  • 21
  • 20
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
  • 8,723
  • 9
  • 41
  • 53
2

You could also use .get(0):

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

To get the first element of the array.

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,406
  • 17
  • 24
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
  • 179
  • 3
  • 12
2

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(Object.values(ary)[0]);
Merak Marey
  • 701
  • 5
  • 15
  • This is vanilla JS, no jQuery, no libs, no-nothing.. :P..it will work if array index does not start at zero, it will work if the world has not ended.... – Merak Marey Sep 19 '19 at 01:25
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,540
  • 15
  • 13
1

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

var arr = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(_.head(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
  • 5
    It literally does `arr[0]` as you can see [here](https://github.com/lodash/lodash/blob/master/head.js) which is why I **strongly** discourage using a gigantic library like lodash for such a small task. – leonheess May 13 '19 at 15:46
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
  • 9
  • 1
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(",");
Mohit Singh
  • 5,633
  • 2
  • 21
  • 24
0
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,230
  • 14
  • 25
  • 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
0

@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
  • 61
  • 1
  • 7
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,052
  • 4
  • 21
  • 48
-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,261
  • 2
  • 17
  • 20
  • 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