Reputation: 39
I am not sure what I am missing. Need the new array to return the first and last element of the passed array.
var firstAndLast = function(array){
var newArray = new Array();
newArray [0] = array[0]
newArray [1] = array[3]
return plate;
}
For Example:
var array = ['one', 3, 'cool', 4];
firstAndLast(array); // returns ['one', 4]
Upvotes: 1
Views: 3372
Reputation: 57934
You need to access the first and last element, and return that in an array. I'm not sure where plate
comes from, but in general your function is 'correct' in the sense that you create a new array and set the first and second elements to the first and last elements of the passed array. You just need to return newArray
.
But what if the the 4th element isn't the last one in the array? Then you'd have to make it more general:
var array = ['one', 3, 'cool', 4];
var firstAndLast = function(arr) {
return [arr[0], arr[arr.length - 1]]; //No need for new Array(), and you can just assign items in positions inline
}
console.log(firstAndLast(array));
The above code reduces the function into 3 lines, as it returns an array literal, with the first element as arr[0]
, the first element of the passed array. The second element is arr[arr.length - 1]
, which is the last element. Consider this:
[1, 2, 3, 4, 5]
The length currently is 5, and the last element is accessed by arr[4]
. Now, just subtract one from the length to get 4, and access the last element. arr[arr.length - 1]
in this case would yield 5
.
Upvotes: 1