How do I merge adjacent elements based on the same attributes of the elements in the array?

const array = [
    { text: "a", style: { bold: true }},
    { text: "b", style: { bold: true }},
    { text: "c", style: { italic: true, bold: true }},
    { text: "d", style: { italic: true }},
    { text: "e", style: { italic: true }},
    { text: "f", style: { underline: true }},
]

an array like this,
expects it to be formatted like this

const formatArray = [
    { text: "ab", style: { bold: true }},
    { text: "c",  style: { italic: true, bold: true }},
    { text: "de", style: { italic: true }},
    { text: "f", style: { underline: true }},
]

splices the text values according to the exact same style attribute. Text has an order requirement, that is, the index of the array, so only adjacent elements with the same style attribute are merged.
ask Daniel to give me some advice!

Mar.16,2021

throw a brick to attract jade, write briefly, if necessary, pay attention to add the judgment of whether the attributes of array, text and style are legal or not.

    function format(array) {
        let newArray = [array[0]];
        array.reduce(function (accumulator, currentItem) {
            if (JSON.stringify(accumulator.style) === JSON.stringify(currentItem.style)) {
                newArray[newArray.length - 1].text += currentItem.text;
            } else {
                newArray.push(currentItem);
            }
            return newArray[newArray.length - 1];
        })
        return newArray;
    }
    const array = [
        {text: 'a', style: {bold: true}},
        {text: 'b', style: {bold: true}},
        {text: 'c', style: {italic: true, bold: true}},
        {text: 'd', style: {italic: true}},
        {text: 'e', style: {italic: true}},
        {text: 'f', style: {underline: true}},
    ];
    let result = format(array);
    console.log(result)
Menu