Js converts an array of one-dimensional objects into a two-dimensional array according to conditions.

excuse me, how to convert the following array arrayFirst, to arrayTwo according to the same index

var arrayFirst = [{
    index: 1,
    datas: han
},
{
    index: 1,
    datas: hu
} {
    index: 2,
    datas: zhang
},
{
    index: 2,
    datas: wang
}

]

var arrayTwo = [[{
    index: 1,
    datas: han
},
{
    index: 1,
    datas: hu
}], [{
    index: 2,
    datas: zhang
},
{
    index: 2,
    datas: wang
}]]

it looks simple, but I don"t know what to do

Mar.29,2021

es6 is very simple to implement. Es5 can be found upstairs

.
var arrayFirst = [
  {
    index: 1,
    datas: 'han'
  },
  {
    index: 1,
    datas: 'hu'
  }, {
    index: 2,
    datas: 'zhang'
  },
  {
    index: 2,
    datas: 'wang'
  }
];

var arrayTwo = Object.values(arrayFirst.reduce((res, item) => {
  res[item.index] ? res[item.index].push(item) : res[item.index] = [item];
  return res;
}, {}));

console.log(arrayTwo)

The

map method is easy to understand:

            var map = new Map();
            var newArr = [];
            arrayFirst.forEach(function(item,i){
                map.has(item.index) ? map.get(item.index).push(item) : map.set(item.index,[item])
            })
            newArr = [...map.values()];
            
            console.log(newArr)

var arrayTwo = [];
var indexGroup = arrayFirst.map(v => v.index);
var flag = [];
for(var i = 0; i<indexGroup.length; iPP) {
    var index = indexGroup[i];
    if(flag[index]) continue;
    flag[index] = 1;
    var groupArray = arrayFirst.filter(v => v.index === index);
    arrayTwo.push(groupArray);
}

categorize first, and then turn the array

function convert (arr) {
    var map1 = {};
    while(arr.length) {
        let current = arr.pop(); // 
        map1[current.index] = map1[current.index] || [];
        map1[current.index].push(current);
    }
    
    return Object.keys(map1).map(key => map1[key]);
}

first sort the array by index, and then cut the array using slice/splice to form a new two-dimensional array

or

use the object to take the value of index as the attribute, and the corresponding array element as the element of the attribute value array. Finally, the attribute value of the object is formed into a new two-dimensional array

.
  

did not reply one by one, everyone's method is very good, deal with the demand, try everyone's plan one by one, thank you again all the friends who answered and participated in this question!

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b679-3465a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b679-3465a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?