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

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

    Lodash has a method for this: https://lodash.com/docs/4.17.10#chunk

    _.chunk([2,3,4,5,6,4,3,5,5], 2); // => [[2,3],[4,5],[6,4],[3,5],[5]]

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

    This combines some of the answers above but without Object.fromEntires. The output is similar to what you would get with minimist.

        const splitParameters = (args) => {
          const split = (arg) => (arg.includes("=") ? arg.split("=") : [arg]);
        
          return args.reduce((params, arg) => [...params, ...split(arg)], []);
        };
        
        const createPairs = (args) =>
          Array.from({ length: args.length / 2 }, (_, i) =>
            args.slice(i * 2, i * 2 + 2)
          );
        
        const createParameters = (pairs) =>
          pairs.reduce(
            (flags, value) => ({
              ...flags,
              ...{ [value[0].replace("--", "")]: value[1] }
            }),
            {}
          );
        
        const getCliParameters = (args) => {
          const pairs = createPairs(splitParameters(args));
          const paramaters = createParameters(pairs);
        
          console.log(paramaters);
        
          return paramaters;
        };
     
    
        //const argsFromNodeCli = process.argv.slice(2); // For node
          
        const testArgs = [
          "--url",
          "https://www.google.com",
          "--phrases=hello,hi,bye,ok"
        ];
        
        const output = getCliParameters(testArgs);
        document.body.innerText = JSON.stringify(output);

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

    It's possible to group an array into pairs/chunks in one line without libraries:

    function chunks(arr, size = 2) {
      return arr.map((x, i) => i % size == 0 && arr.slice(i, i + size)).filter(x => x)
    }
    console.log(chunks([1, 2, 3, 4, 5, 6, 7])) // -> [[1, 2], [3, 4], [5, 6], [7]]

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

    A slightly different approach than using a for loop for comparison. To avoid modifying the original array slice makes a shallow copy since JS passes objects by reference.

    function pairArray(a) {
      var temp = a.slice();
      var arr = [];
    
      while (temp.length) {
        arr.push(temp.splice(0,2));
      }
    
      return arr;
    }
    

    var array = [2,3,4,5,6,4,3,5,5];
    var newArr = pairArray(array);
    
    function pairArray(a) {
      var temp = a.slice();
      var arr = [];
    
      while (temp.length) {
        arr.push(temp.splice(0,2));
      }
    
      return arr;
    }
    
    document.write('<pre>' + JSON.stringify(newArr) + '</pre>');

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

    Here is a short and more generic solution:

    function splitArrayIntoPairs(arr, n) {
     var len = arr.length
      var pairs = []
    
      for (let i = 0; i < len; i += n) {
        var temp = []
        for (var j = i; j < (i + n); j++) {
          if (arr[j] !== undefined) {
            temp.push(arr[j])
          }
        }
        pairs.push(temp)
      }
      return pairs
    }
    

    Where arr is your array and n is no of pairs

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

    Here's a good generic solution:

    function splitInto(array, size, inplace) {
        var output, i, group;
    
        if (inplace) {
            output = array;
    
            for (i = 0; i < array.length; i++) {
                group = array.splice(i, size);
    
                output.splice(i, 0, group);
            }
        } else {
            output = [];
    
            for (i = 0; i < array.length; i += size) {
                output.push(array.slice(i, size + i));
            }
        }
    
        return output;
    }
    

    For your case, you can call it like this:

    var arr= [2,3,4,5,6,4,3,5,5];
    var newarr = splitInto(arr, 2);
    

    The inplace argument determines whether the operation is done in-place or not.

    Here's a demo below:

    function splitInto(array, size, inplace) {
        var output, i, group;
    
        if (inplace) {
            output = array;
    
            for (i = 0; i < array.length; i++) {
                group = array.splice(i, size);
    
                output.splice(i, 0, group);
            }
        } else {
            output = [];
    
            for (i = 0; i < array.length; i += size) {
                output.push(array.slice(i, size + i));
            }
        }
    
        return output;
    }
    
    var arr= [2,3,4,5,6,4,3,5,5];
    var newarr = splitInto(arr, 2);
    
    disp(newarr);
    
    // or we can do it in-place...
    splitInto(arr, 3, true);
    
    disp(arr);
    
    function disp(array) {  
      var json = JSON.stringify(array);
    
      var text = document.createTextNode(json);
      var pre = document.createElement('pre');
    
      pre.appendChild(text);
      document.body.appendChild(pre);
    }

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