[removed] Make an array of value pairs form an array of values

前端 未结 8 1799
灰色年华
灰色年华 2021-01-06 08:40

Is there an elegant, functional way to turn this array:

[ 1, 5, 9, 21 ]

into this

[ [1, 5], [5, 9], [9, 21] ]

I kn

8条回答
  •  一向
    一向 (楼主)
    2021-01-06 09:12

    This is easily done with array.reduce. What the following does is use an array as aggregator, skips the first item, then for each item after that pushes previous item and the current item as a pair to the array.

    const arr = [ 1, 5, 9, 21 ];
    const chunked = arr.reduce((p, c, i, a) => i === 0 ? p : (p.push([c, a[i-1]]), p), []);
    
    console.log(chunked);

    An expanded version would look like:

    const arr = [1, 5, 9, 21];
    const chunked = arr.reduce(function(previous, current, index, array) {
      if(index === 0){
        return previous;
      } else {
        previous.push([ current, array[index - 1]]);
        return previous;
      }
    }, []);
    
    console.log(chunked);

提交回复
热议问题