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

前端 未结 8 1819
灰色年华
灰色年华 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 08:50

    I noticed that the current solutions, in a way, all look ahead or behind (arr[i + 1] or arr[i - 1]).

    It might be useful to also explore an approach that uses reduce and an additional array, defined within a function's closure, to store a to-be-completed partition.

    Notes:

    • Not a one liner, but hopefully easy to understand
    • part doesn't have to be an array when working with only 2 items, but by using an array, we extend the method to work for n-sized sets of items
    • If you're not a fan of shift, you can use a combination of slice and redefine part, but I think it's safe here.
    • partitions with a length less than the required number of elements are not returned

    const partition = partitionSize => arr => {
      const part = [];
      
      return arr.reduce((parts, x) => {
        part.push(x);
        
        if (part.length === partitionSize) {
          parts.push(part.slice());
          part.shift();
        }
        
        return parts;
      }, []);
    };
    
    const makePairs = partition(2);
    const makeTrios = partition(3);
    
    const pairs = makePairs([1,2,3,4,5,6]);
    const trios = makeTrios([1,2,3,4,5,6]);
    
    
    console.log("partition(2)", JSON.stringify(pairs));
    console.log("partition(3)", JSON.stringify(trios));

提交回复
热议问题