js将一个具有相同键值对的一维数组转换成二维数组

这两天,一个前端朋友在面试的笔试过程中遇到了一道类似于“用js实现将一个具有相同code值的一维数组转换成相同code值在一起的二维数组”的题目。他面试过后,把这个问题抛给了我,问我会实现吗?说实话,一开始,我也懵,我唯一能想起来的就是遍历这个一维数组,然后拿数组中的code值来做比较,但是真实现起来就没那么容易了,况且以前我也没有实现过这样的功能,平时的开发中好像也没遇到过这样的功能。

来看看大概的笔试题吧:

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"}
]

以上是一个具有相同code值的一维数组,需要转换成如下的二维数组:

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"} ]  
]

看明白了吧。

那么就来看看如何实现这样的一个效果吧:

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);

实现了一维数组转二维,那么再将转换后的二维数组转换为一维数组呢?还是直接上代码吧:

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://segmentfault.com/q/1010000015730645
https://www.cnblogs.com/liveoutfun/p/9195927.html
https://www.cnblogs.com/front-end-ralph/p/4871332.html

posted @ 2019-03-28 16:37  豫见世家公子  阅读(786)  评论(0编辑  收藏  举报