19

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?

3
  • What does myArray.first do? The first item is the item with the index 0. Commented May 1, 2017 at 4:07
  • 2
    When looking for an array, pretty sure it'd be myArray[0] for the first object and myArray[myArray.length - 1] for the last. Commented May 1, 2017 at 4:08
  • {Rodel: "Betus"} Commented May 1, 2017 at 4:14

13 Answers 13

25

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

Sign up to request clarification or add additional context in comments.

8 Comments

What if the desired output is {Rodel: "Betus"}, as implied by the { firstItem : lastItem } in the OP's code?
@nnnnnn "I am trying to get the first and last item in array and display them in an object."
the output must be {Rodel: "Betus"}
var objOutput = { firstItem : lastItem }; doesnt work
@GaaraItachiUchiha it totally "does work", just not in the way you expect it to. stackoverflow.com/q/4968406/251311
|
18

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

Comments

16

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" }

Comments

13

ES6

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

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

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

console.log(objOutput);

7 Comments

No offense but this looks way worse than the non-ES6 variants :)
Because the above answers are more helpful/cleaner.
@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
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 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.
|
3

Regular answer

const arr = [1, 2, 3, 4];

const first = arr.at(0);
const last = arr.at(-1);

Code golf one-liner

Might be somewhat more readable and easy to digest than other one-liner answers.

const arr = [1, 2, 3, 4];

const [first, last] = [0, -1].map(i => arr.at(i));

Comments

1

Another variation of roli answer

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

1 Comment

Please add a proper explanation to your answer.
1

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" }

Comments

1

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)

Comments

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

3 Comments

Rodel: Bestus Not "firstItem: Bestus"
OP said this a million times
@TyQ. if I asked for a lamborghini million times would you please get it to me?
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);

Comments

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"]
))

1 Comment

It will be better if you add explanation of the answer.
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 ]

Comments

0

Allow me to share an alternative approach: const all = ['food', 'clean', 'cat', 'shower', 'work out'];

console.log(`You have ${all.length} tasks in total.`);
console.log(`First task: ${all[0]}`);
console.log(`Last task: ${all[all.length - 1]}`);

This code efficiently displays the total number of tasks, along with the first and last tasks in the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.