大佬好!将数组元素按条件一维转(push)二维,如何能有更优解?
大佬们好,如代码所示,想要按条件将一维数组按条件转换成二维数组,请问以下代码有没有更好的(更简洁的)解决方法?
首先谢谢 @Admin 2020哥的回答,我找到更好的方法了。嘿嘿。。。。
好点的解决方法
var nameList = ['<5', '<10', '>10']
var detailList = []
var emptyList = []
var list = [1, 3, 5, 7, 4, 9, 10, 11, 12, 13]
var lt5 = list.filter(item=>{return item<5})
var lt10 = list.filter(item=>{return item<10})
var mt10 = list.filter(item=>{return item>10})
emptyList.push(lt5,lt10,mt10)
for(var i in nameList){
detailList.push({name:nameList[i],detailArr:emptyList[i]})
}
console.log(detailList)
问题
var nameList = ['<5', '<10', '>10']
var detailList = []
var emptyList = []
var list = [1, 3, 5, 7, 4, 9, 10, 11, 12, 13]
for (var i in nameList) {
detailList.push({ name: nameList[i], detailArr: [] })
emptyList.push([])
}
for(var i in list){
if(list[i]<5){
emptyList[0].push(list[i])
}
if(list[i]<10){
emptyList[1].push(list[i])
}
if(list[i]>10){
emptyList[2].push(list[i])
}
}
for(var i in detailList){
detailList[i].detailArr = emptyList[i]
}
console.log('detailList',detailList)
-----------------------------------------------------
[{name: "<5", detailArr: [1,3,4]},
{name: "<10", detailArr: [1,3,5,7,4,9]},
{name: ">10", detailArr: [11,12,13]}]