'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 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?



Solution 1:[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:[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:[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:[4]

As of 2021, you can use Array.prototype.at()

let colors = ['red',  'green', 'blue']

let first = colors.at(0) // red
let last = colors.at(-1) // blue

To read more about Array.prototype.at()

Solution 5:[5]

Another variation of roli answer

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

Solution 6:[6]

I prefer using a simple array filter:

const myArray = ['one', 2, 3, 4, 5];
const filterFirstLast = (e, i, a) => i === 0 || i === a.length - 1;
const [ first, last ] = myArray.filter(filterFirstLast);
console.log(first, last); // outputs: 'one', 5

// dealing with insufficient input is another topic (input array length < 2)
console.log(['one'].filter(filterFirstLast )); // outputs: ['one']
console.log([].filter(filterFirstLast )); // outputs: []

transforming to something else is as easy

const obj = { [first]: last }; // will be: { one: 5 }, but never { one: "one" }
// OR, if you allow ['one'] to apply for both, if last is nullish (e.g. undefined, null, ""):
const obj = { [first]: last || first }; // will be: { one: 5 }, can be { one: "one" }

Solution 7:[7]

To make your first and last properties work as you want, define them as properties with "getters" on the array prototype.

(You also have an inconsistency between firstAndLastArray and transformFirstAndLast, which needed to be fixed.)

Returning {firstName: lastName} will not do what you presumably want, since it will yield the key firstName. To use the actual first name as the key, use computed property names ({[firstName]: lastName}).

Object.defineProperties(Array.prototype, {
  first: { get() { return this[0]; }},
  last:  { get() { return this[this.length - 1]; }}
});

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

function firstAndLast(array) {
  var firstItem = myArray.first;
  var lastItem = myArray.last;
  
  return {[firstItem]: lastItem};
}

var display = firstAndLast(myArray);

console.log(display);

Or, much more simply, just

function firstAndLast(array) {
  return {[array[0]]: array[array.length - 1]};
}

If you don't want to, or cannot, use computed property names, then

function firstAndLast(array) {
  var result = {};
  result[array[0]] = array[array.length - 1];
  return result;
}

Solution 8:[8]

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);

Solution 9:[9]

well, I have another idea... for ex.:

const all = ['food', 'clean', 'cat', 'shower', 'work out']
console.log(`you have ${all.length} all!`)
console.log(`Todo: ${all[0]}`)
console.log(`Todo: ${all[all.length - 1]}`)

Solution 10:[10]

try this to find out first and last value of an array

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

let {0 : a ,[array.length - 1] : b} = array;

 var objOutput = {
   first : a,
   last:b
  };

console.log(objOutput)

Solution 11:[11]

In Array :- Check first and last element in array are same or not.. 
function hasSame(arr1, arr2) {
    for(i=0; i <arr1.length ; i++) {
    for(j=0; j <arr2.length ; j++) {
        if(arr1[0] === arr2[0] && arr1[2] ===  arr2[2]) {
            return true
        } else
          return false;
    }
}
}

console.log(hasSame(
    ["white bread", "lettuce", "toast"],
    ["white bread", "tomato", "toast"]
))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Roland
Solution 4 Mudassar
Solution 5
Solution 6 wanderer
Solution 7
Solution 8 Deepak Dixit
Solution 9 Felipe
Solution 10 Krishnamoorthy Acharya
Solution 11 S Gabale