I am trying to get the first and last item in array and display them in an object.
What i did is that I use the first and last function and then assign the first item as the key and the last item as the value.
JavaScript
x
17
17
1
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
2
3
function firstAndLast(array) {
4
5
var firstItem = myArray.first;
6
var lastItem = myArray.last;
7
8
var objOutput = {
9
firstItem : lastItem
10
};
11
12
}
13
14
var display = transformFirstAndLast(myArray);
15
16
console.log(display);
17
however this one gets me into trouble. It says undefined. Any idea why is that?
Advertisement
Answer
I’ve modified your code :
JavaScript
1
18
18
1
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
2
3
function firstAndLast(array) {
4
5
var firstItem = myArray[0];
6
var lastItem = myArray[myArray.length-1];
7
8
var objOutput = {
9
first : firstItem,
10
last : lastItem
11
};
12
13
return objOutput;
14
}
15
16
var display = firstAndLast(myArray);
17
18
console.log(display);
UPDATE: New Modification
JavaScript
1
16
16
1
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
2
3
function firstAndLast(array) {
4
5
var firstItem = myArray[0];
6
var lastItem = myArray[myArray.length-1];
7
8
var objOutput = {};
9
objOutput[firstItem]=lastItem
10
11
return objOutput;
12
}
13
14
var display = firstAndLast(myArray);
15
16
console.log(display);