Get the first and last item in an Array - JS

后端 未结 6 1596
面向向阳花
面向向阳花 2021-01-18 03:01

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 ite

6条回答
  •  情话喂你
    2021-01-18 03:56

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

提交回复
热议问题