Get the first and last item in an Array - JS

后端 未结 6 1647
面向向阳花
面向向阳花 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:31

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

提交回复
热议问题