I need to split an array into N number of arrays based on searching for an element from another array.
consider this scenerio
var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];
now I want a map like
{
env:["6","7","8"],
uat:["2344","wersdf","sdfs"]
}
Note that the array items in test2 and test1 is dynamic.But two test2 values will not be coming one after another in the test array, there will be some items between it.
You could do with Array#Reduce
test2
array and match the index of test
ind+1
.it will target the next argument of delimiteracc[b].push()
test2.indexOf(test[i]) == -1
on else condition.That time you need to break the statement.Then again start the second argument of 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))