◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
提取连续相同项合并算法问题
给定一个按 start 升序排列的数组,其中每个元素包含 start、end 和 content。目标是提取出连续且相同的项,合并为一个新的对象并插入原数组中。合并的条件是 start 和 end 连续。
示例
输入:
[ { "start": 1, "end": 2, "content": [ "a", "b", "e" ] }, //0 { "start": 2, "end": 3, "content": [ "b", "c" ] }, //1 { "start": 3, "end": 4, "content": [ "b", "d" ] }, //2 { "start": 4, "end": 5, "content": [ "d" ] }, //3 { "start": 7, "end": 8, "content": [ "b" ] }, //4 { "start": 9, "end": 11, "content": [ "b", "c" ] } //5 ]
输出:
[ { "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" ] } ]
算法
实现
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)
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。