如何“标准化”对象数组?

问题描述 投票:0回答:1

我不确定“标准化”一词在我的情况下是否正确,所以如果您指出正确的术语,我将不胜感激。我在 DOM 节点方法中发现了这个术语,称为 normalize,它的作用有点相同。

我正在研究文本处理算法,我需要对此进行改造:

{
    type: 'bold',
    data: [
        {
            type: 'italic',
            data: 'italic text'
        },
        {
            type: 'italic',
            data: ' another italic'
        }
    ]
},
{
    type: 'italic',
    data: [
        {
            type: 'bold',
            data: 'bold text'
        },
        {
            type: 'bold',
            data: ' another bold'
        }
    ]
}

进入此:

{
    type: 'bold',
    data: [
        {
            type: 'italic',
            data: 'italic text another italic. bold text another bold'
        }
    ]
}

这里最简单的任务就是合并具有相同类型的相邻节点,但我最终会得到这样的结果:

{
    type: 'bold',
    data: [
        {
            type: 'italic',
            data: 'italic text another italic. '
        },
    ]
},
{
    type: 'italic',
    data: [
        {
            type: 'bold',
            data: 'bold text another bold'
        },
    ]
},

但产量明显过剩。我可以使用哪些算法/数据结构来解决我的问题?此外,文本处理确实是一项艰巨的任务,我很高兴知道是否有关于该主题和/或特定方法/最佳实践的资源。我这样做只是作为我的一个宠物项目来提高我的编码和工程技能,所以不需要推荐使用或窃取开源解决方案:)

algorithm text-processing
1个回答
0
投票

您可以递归地合并具有相同类型的相邻节点。这是您可以使用的功能。 节点 => 你的对象数组

function normalizeNodes(nodes) {
      if (!Array.isArray(nodes) || nodes.length === 0) {
        return nodes;
      }
    
      const result = [];
      let currentType = nodes[0].type;
      let currentData = [nodes[0].data];
    
      for (let i = 1; i < nodes.length; i++) {
        if (nodes[i].type === currentType) {
          currentData.push(nodes[i].data);
        } else {
          result.push({
            type: currentType,
            data: currentData.join(' ')
          });
    
          currentType = nodes[i].type;
          currentData = [nodes[i].data];
        }
      }
    
      result.push({
        type: currentType,
        data: currentData.join(' ')
      });
    
      return result;
    }
© www.soinside.com 2019 - 2024. All rights reserved.