How to slice the array elements between the stars

  • A+
Category:Languages

I need help for y problem, assume the following array:

let arr = [1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", "10","11", "*", "12" , "*"]; 

I want to have an output like this:
first array [1,2,3], second array [4], third array [7,8,9] and so on.

I can find all the * with filter but after that I can slice just with indexOf and lastIndexOf to get the first and the last *.indexOf(filteredElement,2) I can't perform a search for * after specific number, because the user input of the * can be different.

Any suggestions?

Thanks in advance guys

 


You can do it like this with reduce.

Use a temp variable keep on pushing value into it until you don't find a *, as soon as you find a * push this temp variable into output array and reset temp variable.

let arr = [1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", 10,11, "*", 12 , "*"]; let temp = [] let op = arr.reduce((o,c)=>{   if(c !== '*'){     temp.push(c)   } else {    if(temp.length){     o.push(temp); }     temp=[];   }   return o; },[]) console.log(op)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: