js argumentsjs将⼀个具有相同键值对的⼀维数组转换成⼆维数组
这两天,⼀个前端朋友在⾯试的笔试过程中遇到了⼀道类似于“⽤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.de) ? (de).push(item) : map.de, [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值,也就是说该数组的各个元素将会依次成为被调⽤函数的各个参数。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论