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

前端 未结 6 1924
自闭症患者
自闭症患者 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:28

    You can call:

    arr.slice(Math.max(arr.length - 5, 1))
    

    If you don't want to exclude the first element, use

    arr.slice(Math.max(arr.length - 5, 0))
    
    0 讨论(0)
  • 2020-11-30 20:28

    var y = [1,2,3,4,5,6,7,8,9,10];
    
    console.log(y.slice((y.length - 5), y.length))

    you can do this!

    0 讨论(0)
  • 2020-11-30 20:30

    Here is one I haven't seen that's even shorter

    arr.slice(1).slice(-5)

    Run the code snippet below for proof of it doing what you want

    var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],
      arr2 = [0, 1, 2, 3];
    
    document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);

    Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.

    _.slice(_.rest(arr), -5)

    0 讨论(0)
  • 2020-11-30 20:32

    Try this:

    var array = [1, 55, 77, 88, 76, 59];
    var array_last_five;
    array_last_five = array.slice(-5);
    if (array.length < 6) {
         array_last_five.shift();
    }
    
    0 讨论(0)
  • 2020-11-30 20:49

    If you are using lodash, its even simpler with takeRight.

    _.takeRight(arr, 5);

    0 讨论(0)
  • 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]))
    );

    0 讨论(0)
提交回复
热议问题