I would like to join
the items in a string array that contain values and keep the empty items.
JavaScript
x
3
1
// example array
2
const sentenceSplit = ["There", "is", "a", "", "", "cat", "in", "", "three"];
3
For the above example, I would like to achieve the following outcome:
JavaScript
1
2
1
["There is a", "", "", "cat in", "", "three"]
2
I tried using reduce
, but couldn’t figure out the solution.
JavaScript
1
4
1
const result = sentenceSplit.reduce((acc, val) => {
2
// can't figure out logic
3
});
4
Advertisement
Answer
You can use reduce
and check whether the last produced entry or the current string is empty. If so, the current string should be a separate entry, otherwise it should be concatenated to the previous entry:
JavaScript
1
12
12
1
const sentenceSplit = ["There", "is", "a", "", "", "cat", "in", "", "three"];
2
3
let result = sentenceSplit.reduce((acc, str) => {
4
if (str && acc[acc.length-1]) {
5
acc[acc.length-1] += " " + str;
6
} else {
7
acc.push(str);
8
}
9
return acc;
10
}, []);
11
12
console.log(result);