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

后端 未结 14 1588
广开言路
广开言路 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: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);

提交回复
热议问题