How do you split an array into array pairs in JavaScript?

后端 未结 14 1582
广开言路
广开言路 2020-12-08 09:49

I want to split an array into pairs of arrays.

var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]

would be

var newarr = [
    [2, 3],
           


        
14条回答
  •  时光取名叫无心
    2020-12-08 10:20

    Here is another generic solution that uses a generator function.

    /**
     * Returns a `Generator` of all unique pairs of elements from the given `iterable`.
     * @param iterable The collection of which to find all unique element pairs.
     */
    function* pairs(iterable) {
        const seenItems = new Set();
        for (const currentItem of iterable) {
            if (!seenItems.has(currentItem)) {
                for (const seenItem of seenItems) {
                    yield [seenItem, currentItem];
                }
                seenItems.add(currentItem);
            }
        }
    }
    
    const numbers = [1, 2, 3, 2];
    const pairsOfNumbers = pairs(numbers);
    
    console.log(Array.from(pairsOfNumbers));
    // [[1,2],[1,3],[2,3]]

    What I like about this approach is that it will not consume the next item from the input until it actually needs it. This is especially handy if you feed it a generator as input, since it will respect its lazy execution.

提交回复
热议问题