Group an array to form three arrays based on the index

后端 未结 3 1523
梦谈多话
梦谈多话 2021-01-29 12:44

I want to sort an array in a way that it gives back three arrays. So

var myArray = [\'1\',\'2\',\'3\',\'1\',\'2\',\'3\',\'1\',\'2\',\'3\',\'1\',\'2\',\'3\',\'1\'         


        
相关标签:
3条回答
  • 2021-01-29 13:08
    var myArray = ['1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3'];
    
    var myArray1 = [];
    var myArray2 = [];
    var myArray3 = [];
    for(var i = 0; i < myArray.length;) {
        myArray1.push(myArray [i++]); 
        myArray2.push(myArray [i++]);
        myArray3.push(myArray [i++]);
    }
    
    0 讨论(0)
  • 2021-01-29 13:14

    You could create a generic function which will group the array based on the n provided. Based on the result of index % n, push them into specific arrays. Here, n = 3. If you use i % 2, this will distribute the numbers into 2 arrays based on odd and even indices.

    const myArray = ['1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3'];
    
    function group(array, n) {
      return myArray.reduce((acc, number, i) => {
        acc[i % n] = acc[i % n] || [];
        acc[i % n].push(number);
        return acc;
      }, [])
    }
    
    const grouped = group(myArray, 3);
    
    console.log(JSON.stringify(grouped[0]))
    console.log(JSON.stringify(grouped[1]))
    console.log(JSON.stringify(grouped[2]))

    0 讨论(0)
  • 2021-01-29 13:19

    If you're looking for high-order solution (using methods, like Array.prototype.reduce()) following approach might work:

    const arr = ['1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3'];
    
    const [arr1,arr2,arr3] = arr.reduce((res,e,i) => (res[i%3].push(e),res), [[],[],[]]);
    
    console.log(`arr1 = ${JSON.stringify(arr1)}`);
    console.log(`arr2 = ${JSON.stringify(arr2)}`);
    console.log(`arr3 = ${JSON.stringify(arr3)}`);
    .as-console-wrapper{min-height:100%}

    p.s. got a sneak peek at this (universal) solution to make mine a bit more compact

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