◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
合并相同连续项
如何从给定的数组中提取并合并连续的相同项,得到包含合并后的连续项的新数组?下文提供了一种实现该算法的方案。
算法步骤:
使用 reduce 迭代输入数组,执行以下操作:
遍历每个元素 item 中的 content,并为每个 content 元素执行以下操作:
示例代码:
let arr = [ { "start": 1, "end": 2, "content": [ "a", "b", "e" ] }, { "start": 2, "end": 3, "content": [ "b", "c" ] }, { "start": 3, "end": 4, "content": [ "b", "d" ] }, { "start": 4, "end": 5, "content": [ "d" ] }, { "start": 7, "end": 8, "content": [ "b" ] }, { "start": 9, "end": 11, "content": [ "b", "c" ] } ]; let obj = {}; let list = arr.reduce((list, item, index, arr) => { item.content.foreach(citem => { let i = index; let next, cindex; while ((next = arr[i + 1]) && arr[i].end === next.start && (cindex = next.content.indexof(citem)) >= 0) { i++; next.content.splice(cindex, 1); } let end = arr[i].end; let key = item.start + '-' + end; if(!obj[key]){ list.push(obj[key] = { start: item.start, end, content: [citem] }); }else{ obj[key].content.push(citem); } }); return list; }, []); console.log(list);
输出:
[ { "start": 1, "end": 2, "content": [ "A", "E" ] }, { "start": 1, "end": 4, "content": [ "B" ] }, { "start": 2, "end": 3, "content": [ "C" ] }, { "start": 3, "end": 5, "content": [ "D" ] }, { "start": 7, "end": 8, "content": [ "B" ] }, { "start": 9, "end": 11, "content": [ "B", "C" ] } ]
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。