0
votes

input string: "abc def, ghi jkl, mnopq"
Desired Output Arrays: ["abc","def"] ["ghi", "jkl"] ["mnopq"]

The input can be any combination of phrases separated by spaces, those phrases are then separated by commas. I need to make a new array for each input string which is followed by a comma. When those arrays are created they have to be split by " ".

Below is the code to split the string into array values using a comma as a separator:

str = "abc def, ghi jkl, mnopq";     
const commaSeparatedArray = this.str.split(',').filter(s => s.slice(-1) !== ' ');

console.log(commaSeparatedArray);

Not sure if the next step to take here is a for or while loop for such actions or a javascript prototype?

Link to stackblitz: https://stackblitz.com/edit/angular-ivy-vbdae5?file=src%2Fapp%2Fapp.component.ts

5

5 Answers

5
votes

The following gives you an array of array. If something similar you are looking for.

var s = "abc def, ghi jkl, mnopq";
var result = s.split(',').map(a=>a.trim().split(' '));
console.log(result);
2
votes

str = "abc def, ghi jkl, mnopq";

//you need to again split and filter out the empty string to get the desired output.

const commaSeparatedArray = this.str.split(',').map(item => {
  const d = item.split(' ').filter(i => i);
  return [...d]
})
console.log(commaSeparatedArray)
1
votes

You basically just want to do two rounds of splitting

const str = "abc def, ghi jkl, mnopq";

const result = str.split(/,\s*/).map(substr => substr.split(/\s+/))

console.info(result)

That is

  1. Split the string on comma + zero-or-more spaces
  2. Then map each entry to another array by splitting that string on whitespace
1
votes

const str = "abc def, ghi jkl, mnopq";

const commaSeparatedArray = str.split(",");

const result = commaSeparatedArray.reduce((acc, stringWithspaces) => {
  return [...acc, stringWithspaces.split(" ").filter(string=> string)];
}, []);

console.log(result);
1
votes

I hope I have been helpful

var str = "abc def, ghi jkl, mnopq";
var res = str.split(', ').map(x => x.split(' '));
console.log(res);