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.
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray.first;
var lastItem = myArray.last;
var objOutput = {
firstItem : lastItem
};
}
var display = transformFirstAndLast(myArray);
console.log(display);
however this one gets me into trouble. It says undefined. Any idea why is that?
Do like this :-
ES6
well, I have another idea... for ex.:
I've modified your code :
UPDATE: New Modification
To make your
first
andlast
properties work as you want, define them as properties with "getters" on the array prototype.(You also have an inconsistency between
firstAndLastArray
andtransformFirstAndLast
, which needed to be fixed.)Returning
{firstName: lastName}
will not do what you presumably want, since it will yield the keyfirstName
. To use the actual first name as the key, use computed property names ({[firstName]: lastName}
).Or, much more simply, just
If you don't want to, or cannot, use computed property names, then
With ES6 and destructuring: