我需要根据从另一个数组中搜索元素来将一个数组拆分为N个数组。
考虑此场景
var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];
现在我想要一张类似的地图
{
env:["6","7","8"],
uat:["2344","wersdf","sdfs"]
}
请注意,test2和test1中的数组项是动态的。但是在测试数组中,两个test2值不会一个接一个地出现,它们之间会有一些项目。
您可以使用Array#Reduce
test2
数组并匹配test
的索引ind+1
的forloop。它将针对定界符的下一个参数acc[b].push()
将值传递到数组后test2.indexOf(test[i]) == -1
检测下一个定界符。这时您需要中断语句。然后再次启动test2
的第二个参数function maper(test, test2) {
return test2.reduce((acc, b) => {
let ind = test.indexOf(b); //detect starting index of delimiter
if (ind > -1) {
acc[b] = acc[b] || [];
for (var i = ind+1; i < test.length; i++) {
if (test2.indexOf(test[i]) == -1) { //detet next delimiter reach
acc[b].push(test[i])
}else{
break;
}
}
}
return acc
}, {})
}
var test = ["1", "2", "3", "env", "6", "7", "8", "uat", "2344", "wersdf", "sdfs"];
var test2 = ["env", "uat"];
console.log(maper(test, test2))
var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];
var indexArray = [];
test2.map(key=>{
var index = test.indexOf(key);
indexArray.push(index);
})
var obj = {};
for(var i = 0; i<indexArray.length; i++){
var part = test.slice(indexArray[i]+1, indexArray[i+1]);
obj = {...obj,[test2[i]]: [ ...part]};
}
console.log("obj = ", obj);