javascript经典面试题:写函数实现按下标插入功能

题目:现在有一个数组存放字符串数据:

['item1', 'item2', 'item3', 'item4', 'item5']

有另外一个数组存放一组对象:

[
  { content: 'section1', index: 0 },
  { content: 'section2', index: 2 }
]

它每个对象表示的是会往原来的数组的 index 坐标插入 content 数据(index 不会重复):

   0      1      2      3      4
 item1  itme2  item3  item4  item5
^             ^ 
|             |

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']

答案:

const injectSections = (items, sections) => {
  /* 需要插入坐标对应数据存放到 map 里面 */
  const sectionsMap = new Map(sections.map(({ index, content }) => [index, content]))
  /* 新建一个数组,然后往里面 push 原来数组的数据 */
  return items.reduce((ret, item, index) => {
    /* push 的时候先检查 map 里面有没有,有的话先 push map 里面的数据 */
    if (sectionsMap.has(index)) ret.push(sectionsMap.get(index))
    /* 再 push 原来的数据 */
    ret.push(item)
    return ret
  }, [])
}
THE END