17

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?

12 Answers12

23

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);
Ashraf
  • 2,612
  • 1
  • 20
  • 35
  • 1
    What if the desired output is `{Rodel: "Betus"}`, as implied by the `{ firstItem : lastItem }` in the OP's code? – nnnnnn May 01 '17 at 04:12
  • @nnnnnn "I am trying to get the first and last item in array and `display them` in an object." – Ashraf May 01 '17 at 04:13
  • the output must be {Rodel: "Betus"} –  May 01 '17 at 04:14
  • var objOutput = { firstItem : lastItem }; doesnt work –  May 01 '17 at 04:15
  • @GaaraItachiUchiha it totally "does work", just not in the way you expect it to. http://stackoverflow.com/q/4968406/251311 – zerkms May 01 '17 at 04:16
  • @Ashraf - If you go just on that sentence then `console.log(myArray)` is the only code needed, because `myArray` is already a type of object. – nnnnnn May 01 '17 at 04:20
  • Not that it necessarily matters, but if the first item isn't of a simple type (`boolean`, `number`, `string`), then your edited answer would fail. – Emil S. Jørgensen May 01 '17 at 06:51
  • @EmilS.Jørgensen I agree , the requirement itself is a bit strange . – Ashraf May 01 '17 at 09:19
14

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" }
Roland
  • 24,554
  • 4
  • 99
  • 97
13

ES6

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

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

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

console.log(objOutput);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • No offense but this looks way worse than the non-ES6 variants :) – Bataleon Jun 18 '19 at 12:28
  • Because the above answers are more helpful/cleaner. – Bataleon Jun 19 '19 at 10:01
  • 6
    @Bataleon the value of this answer is that it is short and different than other answers, so it gives more choice to the programmer and increases his knowledge of potential opportunities – Kamil Kiełczewski Jun 19 '19 at 10:14
  • Yes, but the cognitive load of understanding the code is higher than the alternative approaches. Should we not all be aiming to write _readable_ code? :) – Bataleon Jun 20 '19 at 07:53
  • 3
    @Bataleon vote down means "wrong", this is not a wrong answer. If you don't like an answer, feel free to comment but if it's really bad it won't get enough vote ups. Vote down is a strong negative, that's why StackOverflow will give you negative points when you vote down, so please use them carefully. – orad Aug 21 '19 at 16:39
  • @orad Thanks, I didn't realise down voting was seen as so "serious". To quote the SO docs: "Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect." I have since removed my downvote (because the answer works). However, it seems the response is more about the author showing off their JavaScript chops, rather than providing a _readable_ solution. – Bataleon Aug 22 '19 at 08:49
  • While this might look pretty and fancy, I would not recommended it as it could potentially trigger two copies!! – Valentino Miori Nov 09 '21 at 09:03
13

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

Mudassar
  • 508
  • 4
  • 13
2

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" }
wanderer
  • 46
  • 2
1

Another variation of roli answer

function firstAndLast(array) {
    return { [[...array].shift()]: [...array].pop() };
}
Rezan Moh
  • 336
  • 2
  • 7
0

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;
}
0

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);
Deepak Dixit
  • 1,510
  • 15
  • 24
0

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]}`)
Felipe
  • 101
  • 10
0

Please try this to find out the 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)
0
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"]
))
S Gabale
  • 1
  • 3
0

Change last to first

const x=[1,2,3]
x.unshift(x.splice(x.length-1,1)[0])
console.log(x) // [ 3, 1, 2 ]