How to split a string into an array based on every FOUR commas?

后端 未结 3 1072
独厮守ぢ
独厮守ぢ 2021-01-06 23:21

so I\'m trying to split a string into an array based on the amount of commas, how do I do that? Say my string is as such;

var string = \"abc, def, ghi, jkl,         


        
3条回答
  •  清酒与你
    2021-01-06 23:58

    You can use split and reduce also to achieve this :

    let array = str.split(", ").reduce((prev, curr, i) => {
          if(i%4 === 0){
             prev.push([]);
          }
          prev[prev.length - 1].push(curr);
          return prev;
       }, [])
    

提交回复
热议问题