【发布时间】:2016-09-12 23:19:08
【问题描述】:
我有一个包含字母和颜色的数组。
const a = [
{char: 'h', color: 'red'},
{char: 'e', color: 'red'},
{char: 'y', color: 'red'},
{char: ' ', color: 'green'},
{char: 't', color: 'red'},
{char: 'h', color: 'red'},
{char: 'e', color: 'red'},
{char: 'r', color: 'red'},
{char: 'e', color: 'red'}
];
我想写一个函数把它和一个字符串合并:
const s = 'hey, howdy there';
同时保留字符到颜色的原始映射。例如,组成hey 和there 的字符应该仍然是红色, 是绿色,如最初在数组 a 中绘制的那样,而新字符默认为任意值,例如黄色,旧字符被删除.所以,这个函数的输出会给我类似的东西:
res = [
{char: 'h', color: 'red'},
{char: 'e', color: 'red'},
{char: 'y', color: 'red'},
{char: ',', color: 'yellow'},
{char: ' ', color: 'green'},
{char: 'h', color: 'yellow'},
{char: 'o', color: 'yellow'},
{char: 'w', color: 'yellow'},
{char: 'd', color: 'yellow'},
{char: 'y', color: 'yellow'},
{char: ' ', color: 'yellow'},
{char: 't', color: 'red'},
{char: 'h', color: 'red'},
{char: 'e', color: 'red'},
{char: 'r', color: 'red'},
{char: 'e', color: 'red'}
];
一种方法可能是从const a 中提取字符,将它们连接成一个字符串并在空格上分割,这样你就有了一个单词数组。用字符串 s 重复。循环遍历字符串 s 的新拆分数组,直到该数组与原始数组 a 拆分不匹配。这将发生在, 字符上。
这是我不知道如何进行的地方。在一个简单的情况下,只有两个单词,您可以只保留第一个单词并将其他所有内容替换为字符串 s 拆分中的新单词。但是,在我提供的情况下,我将值添加到新字符串(即, howdy),同时保留旧数组的值(there)。
我想 git 用来区分文本的算法在这里可以工作,但我不确定如何复制它,或者在这个用例中它是否有效。
编辑: 我对其进行了一些修改,因为我意识到其中一些不一致。
【问题讨论】:
-
我认为您需要研究如何确定两个字符串之间的编辑差异。这应该告诉您
, howdy已插入,您可以将其标记为黄色。 -
不确定我理解你的目的。该问题将数组
const a称为“映射”,但作为一个数组,它不仅仅是一个映射,因为它保持顺序。它还包含重复的字符,例如“hey”中的“e”和“there”中的“e”。这些键的值在您的示例中是相同的,但它们有时会有所不同吗?真正的映射看起来像{ h: "red", e: "red" ... },没有排序,也没有重复的键。将其作为输入/输出处理的算法将非常简单。这就是你想要的吗? -
@Barmar 编辑差异是我一直在寻找的,但没有词汇来描述。我做了一些研究,我需要的是 myer 的 diff 算法。感谢您的提示!
标签: javascript arrays string algorithm merge