In a javascript array, how do I get the last 5 elements, excluding the first element?

前端 未结 6 1951
自闭症患者
自闭症患者 2020-11-30 20:19
[1, 55, 77, 88] // ...would return [55, 77, 88]

adding additional examples:

[1, 55, 77, 88, 99, 22, 33, 44] // ...wo         


        
6条回答
  •  广开言路
    2020-11-30 20:49

    ES6 way:

    I use destructuring assignment for array to get first and remaining rest elements and then I'll take last five of the rest with slice method:

    const cutOffFirstAndLastFive = (array) => {
      const [first, ...rest] = array;
      return rest.slice(-5);
    }
    
    cutOffFirstAndLastFive([1, 55, 77, 88]);
    
    console.log(
      'Tests:',
      JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),
      JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),
      JSON.stringify(cutOffFirstAndLastFive([1]))
    );

提交回复
热议问题