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

前端 未结 8 1742
灰色年华
灰色年华 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:11

    I'm sure there is an elegant way, programmatically, but, mathematically I can't help seeing that each new pair has an index difference of 1 from the original array.

    If you (later) have the need to turn your array [ 1, 5, 9, 21, 33 ] into [ [1, 9], [5, 21], [9, 33] ], you can use the fact that the difference between the indices is 2.

    If you create code for the index difference of 1, extending this would be easy.

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

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