Skip to content
Advertisement

Join specific items in an array [closed]

I would like to join the items in a string array that contain values and keep the empty items.

// example array
const sentenceSplit = ["There", "is", "a", "", "", "cat", "in", "", "three"];

For the above example, I would like to achieve the following outcome:

["There is a", "", "", "cat in", "", "three"]

I tried using reduce, but couldn’t figure out the solution.

const result = sentenceSplit.reduce((acc, val) => {
  // can't figure out logic
});

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:

const sentenceSplit = ["There", "is", "a", "", "", "cat", "in", "", "three"];

let result = sentenceSplit.reduce((acc, str) => {
    if (str && acc[acc.length-1]) {
        acc[acc.length-1] += " " + str;
    } else {
        acc.push(str);
    }
    return acc;
}, []);

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement