首页 > 解决方案 > 在JavaScript中的数组中每n个元素插入一个元素

问题描述

我正在尝试做的事情的前提是:

假设我们有以下数组:

let arr = ["hello", "nice", "stack", "hi", "question", "random"];

我们想要做的是达到一个点,在该点我们可以"cat"每两个现有的数组元素插入(推入)一个元素到数组中(比如说)。

新数组将产生以下内容:

"hello"
"nice"
"cat" // new element
"stack"
"hi"
"cat" // new element
// so on and so forth...

在减少运行时间的同时实现这一点的最佳方法是什么?

标签: javascriptarrays

解决方案


使用Array#reduce

const 
  arr = ["hello", "nice", "stack", "hi", "question", "random"],
  newElem = "cat",
  n = 2;
  
const res = arr.reduce((list, elem, i) => {
  list.push(elem);
  if((i+1) % n === 0) list.push(newElem);
  return list;
}, []);

console.log(res);


推荐阅读