I have an array of strings in JavaScript and I want to split them into "paragraphs" by grouping them together based on blank lines. for instance:
["a", "b", "", "c", "", "d", "e", "f"] => [["a", "b"], ["c"], ["d", "e", "f"]]
It's exactly like string.split() but with an array as the input instead of a string.
Of course, I could write this function myself using a loop or maybe reduce but it sounds like quite a generic function. I'm wondering if there is anything in lodash or similar that could do it.
3 Answers 3
you mean like this ?
let data = ["a", "b", "", "c", "", "d", "e", "f"]
let temp = []
let result = []
data.map(x => {
if(x) {
temp.push(x)
} else {
result.push(temp)
temp = []
}
})
temp.length != 0 ? result.push(temp) : ''
console.log(result)
2 Comments
I'm not sure lodash can resolve it at this time.
In the meanwhile, you can do the trick in this way
const array = ["a", "b", "", "c", "", "d", "e", "f"];
const delimiter = ",";
var index = 0;
const result = array.reduce((acc, curr) => {
if(curr == "") index++;
else acc[index] = (acc[index] || "") + delimiter + curr;
return acc;
}, [])
console.log(result.map(r => r.substring(1).split(delimiter)));
8 Comments
lodash will have the solution soon in this case. So that is the reason why I still wanna answer @Andreas["a", b", "", "c,d",] and you get the second group as ["c", "d"]. Adjusting the delimiter doesn't help much as it might still clash with the data. Further problem is if the data is not a string: [1, 2, "", 3, 4] will have the data types changed by this. having objects will just fail even worse. Ultimately splitting is fundamentally flawed approach and not suitable as a generic solution.If it's a simple formula that doesn't use loops, you can create it like this:
arr.map(v => v || ",").join("").split(",").map(v => v.split(""))
If you plan on getting paragraphs values a lot, you might want to define a function for it.
First, put this in your code somewhere:
Array.prototype.paragraphs = function(){
return this.map(v => v || ",").join("").split(",").map(v => v.split(""))
}
Now:
["a", "b", "", "c", "", "d", "e", "f"].paragraphs()
lodashfor it. If someone has that information, he could share. Otherwise, this could end-up as an issue for a 'feature' in lodash's github. So why do you have totake it so hard?