0

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.

1
  • 2
    array2[0] + '-' + array2[array2.length - 1] Commented Mar 6, 2015 at 14:28

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

2 Comments

question was to combine the two, connected with a dash.
@Shishdem -- Altho I think OP could handle concatenating them, I updated the answer.
0
var a = array2[0] + '-' + array2[array2.length-1];

3 Comments

Try to explain your answers. The "try this" answers aren't as helpful.
OK, I will, I thought it was self-explanatory
It is pretty basic, so for most people it would be. However, it's not self explanatory for people that will be looking for these kinds of answers. It's all about making the answer useful for more than just the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.