Open kitewhere opened 6 years ago
const injectSections = (items, sections) => {
sections.forEach(
(v,i)=>{
items[v.index]=[v.content,items[v.index]]
}
);
return [].concat.apply([],items);
}
问题在于插入后 原数组的 index 改变了 后面的就要重新计算插入点 一般的解法是 先插入点 index 排序 先插入后面的 对前面的 index 不会有影响
conact 的解法 把插入点的数据变成数组 item0 变成 [section1, item0] 最后在 conact 夷平
现在有一个数组存放字符串数据:
['item1', 'item2', 'item3', 'item4', 'item5'] 有另外一个数组存放一组对象:
它每个对象表示的是会往原来的数组的 index 坐标插入 content 数据(index 不会重复):
section1 section2
最后结果是:['section1', 'item1', 'item2', 'section2', 'item3', 'item4', 'item5'] 请你完成 injectSections 函数,可以达到上述的功能:
injectSections( ['item1', 'item2', 'item3', 'item4', 'item5'], [ { content: 'section1', index: 0 }, { content: 'section2', index: 2 } ] ) // => ['section1', 'item1', 'item2', 'section2', 'item3', 'item4', 'item5']