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

后端 未结 14 1576
广开言路
广开言路 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:09

    Yet another that's a bit of a mish-mash of the already-posted answers. Adding it because having read the answers I still felt things could be a little easier to read:

    var groups = [];
    
    for(var i = 0; i < arr.length; i += 2)
    {
        groups.push(arr.slice(i, i + 2));
    }
    
    0 讨论(0)
  • 2020-12-08 10:09

    const items = [1, 2, 3, 4, 5];
    
    const createBucket = (bucketItems, bucketSize) => buckets => {
      return bucketItems.length === 0 ? buckets : [...buckets, bucketItems.splice(0, bucketSize)];
    };
    
    const bucketWithItems = items.reduce(createBucket([...items], 4), []);

    0 讨论(0)
  • 2020-12-08 10:17

    There's no pre-baked function to do that, but here's a simple solution:

    var splitPairs = function(arr) {
        var pairs = [];
        for (var i=0 ; i<arr.length ; i+=2) {
            if (arr[i+1] !== undefined) {
                pairs.push ([arr[i], arr[i+1]]);
            } else {
                pairs.push ([arr[i]]);
            }
        }
        return pairs;
    };
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 10:21

    I would use lodash for situations like this.

    Here is a solution using _.reduce:

    var newArr = _(arr).reduce(function(result, value, index) {
      if (index % 2 === 0)
        result.push(arr.slice(index, index + 2));
    
      return result;
    }, []);
    

    var arr = [2,3,4,5,6,4,3,5,5];
    
    var newArr = _(arr).reduce(function(result, value, index) {
      if (index % 2 === 0)
        result.push(arr.slice(index, index + 2));
      
      return result;
    }, []);
    
    document.write(JSON.stringify(newArr)); // [[2,3],[4,5],[6,4],[3,5],[5]]
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-08 10:22

    There is now the flexible Array#flatMap(value, index, array):

    const pairs = arr.flatMap((_, i, a) => i % 2 ? [] : [a.slice(i, i + 2)]);
    

    And the possibly more efficient, but goofy looking Array.from(source, mapfn?):

    const pairs = Array.from({ length: arr.length / 2 }, (_, i) => arr.slice(i * 2, i * 2 + 2))
    
    0 讨论(0)
提交回复
热议问题