一维数组转换成二维数组

如下图,在一维数组中若将含有相同字段属性的归纳,转换为二维数组

  • 一维数组
let arr = [
      {code: "China", name: "xiaohuai"},
      {code: "Africa", name: "neiLuoBi"},   
      {code: "Asia", name: "hanGuo"},
      {code: "China", name: "tnnyang"},
      {code: "Africa", name: "nanFei"},      
      {code: "China", name: "yangMan"}
]
  • 二维数组
let arr = [
    [ {code: "China", name: "xiaohuai"}, {code: "China", name: "tnnyang"}, {code: "China", name: "yangMan"} ],
    [ {code: "Africa", name: "neiLuoBi"}, {code: "Africa", name: "nanFei"} ],
    [ {code: "Asia", name: "hanGuo"} ]  
]
1. 将一维数组转换成二维数组
let arr = [
      {code: "China", name: "xiaohuai"},
      {code: "Africa", name: "neiLuoBi"},   
      {code: "Asia", name: "hanGuo"},
      {code: "China", name: "tnnyang"},
      {code: "Africa", name: "nanFei"},      
      {code: "China", name: "yangMan"}
]

// 重点
var map = new Map();
var newArr = [];
arr.forEach(item => {
     map.has(item.code) ? map.get(item.code).push(item) : map.set(item.code, [item]);
})

newArr = [...map.values()];
    
console.log(newArr);
2. 将二维数组转换成一维数组
let arr = [
    [ {code: "China", name: "xiaohuai"}, {code: "China", name: "tnnyang"}, {code: "China", name: "yangMan"} ],
    [ {code: "Africa", name: "neiLuoBi"}, {code: "Africa", name: "nanFei"} ],
    [ {code: "Asia", name: "hanGuo"} ]  
]

//方法一:
function reduceDimension(arr) {
      var reduced = [];
      for (var i = 0; i < arr.length; i++) {
          for (var j = 0; j < arr[i].length; j++) {
              reduced.push(arr[i][j]);
          }
      }
      return reduced;
}

console.log(reduceDimension(arr));

//方法二:
console.log([].concat.apply([], arr));

方法一是循环遍历,没啥说的。方法二有必要说一下,apply方法会调用一个函数,apply方法的第一个参数会作为被调用函数的this值,apply方法的第二个参数(一个数组,或类数组的对象)会作为被调用对象的arguments值,也就是说该数组的各个元素将会依次成为被调用函数的各个参数

本文参考:

https://www.cnblogs.com/tnnyang/p/10616011.html

你可能感兴趣的:(一维数组转换成二维数组)