mep
mep

Reputation: 67

return first and last value in an array

How can I return the first and last word from this array?

var array2 = ['milk','juice','lemonade','soda','water'];

I want it to return "milk-water" with the "-" combinding them.

Im not sure which of the array methods to use for this.

Upvotes: 0

Views: 75

Answers (2)

n-dru
n-dru

Reputation: 9420

var a = array2[0] + '-' + array2[array2.length-1];

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Use 0 for the first, and array.length - 1 for the last

var firstVal = array2[0];
var lastVal = array2[array2.length - 1]
var combo = firstVal + "-" + lastVal;

Upvotes: 4

Related Questions