Skip to content Skip to sidebar Skip to footer

Get The First And Last Item In An Array - JS

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 an

Solution 1:

I've modified your code :

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

function firstAndLast(array) {

var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];

 var objOutput = {
   first : firstItem,
   last : lastItem
  };

return objOutput;
}

var display = firstAndLast(myArray);

console.log(display);

UPDATE: New Modification

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

function firstAndLast(array) {

var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];

var objOutput = {};
objOutput[firstItem]=lastItem

return objOutput;
}

var display = firstAndLast(myArray);

console.log(display);

Solution 2:

ES6

var objOutput = { [myArray[0]]: [...myArray].pop() }

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

var objOutput = { [myArray[0]]: [...myArray].pop() }

console.log(objOutput);

Solution 3:

With ES6 and destructuring:

const myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

const { 0: first, length, [length -1]: last } = myArray //getting first and last el from array
const obj = { first, last }

console.log(obj) // {  first: "Rodel",  last: "Betus" }

Solution 4:

Another variation of roli answer

function firstAndLast(array) {
    return { [[...array].shift()]: [...array].pop() };
}

Solution 5:

Do like this :-

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

function firstAndLast(myArr) {

    var firstItem = myArr[0];
    var lastItem = myArr[myArr.length - 1];
    var objOutput = {}; 
    objOutput[firstItem] = lastItem;
    return objOutput;
}

var display = firstAndLast(myArray);

console.log(display);

Post a Comment for "Get The First And Last Item In An Array - JS"