如何根据数组内的元素的相同属性将相邻的元素合并?

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 }},
]

类似这样的数组,
期望格式化后是这样的

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

根据完全相同的style属性将text值拼接, text有顺序要求,就是数组的索引,所以只合并相邻的具有相同style属性的元素。
请大牛们指点迷津!

阅读 3.6k
1 个回答

抛砖引玉,简单写了一下,如有需要,注意加上array和text、style属性是否合法的判断。

    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)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题