Filippo Fonseca
Filippo Fonseca

Reputation: 84

Insert an element every n elements in an array in JavaScript

The premise of what I'm trying to do is the following:

Let's say we have the following array:

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

What we want to do is reach a point in which we can insert (push) an element into the array (let's say "cat" as an example) every two existing array elements.

The new array would yield the following:

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

What's the best way to implement this while reducing runtime?

Upvotes: 3

Views: 4054

Answers (5)

Hassan Imam
Hassan Imam

Reputation: 22574

You can use array#flatMap and insert new word after every given interval.

let arr = ["hello", "nice", "stack", "hi", "question", "random"],
    interval = 2,
    word = 'cat',
    result = arr.flatMap((w,i) => (i+1) % interval === 0 ? [w, word] : w);
console.log(result);

Upvotes: 2

Majed Badawi
Majed Badawi

Reputation: 28434

Using 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);

Upvotes: 6

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23510

Using for loop and splice

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

let index = 2
let result = [...arr]
let currentPosition = 0
for (let i = 0; i < Math.floor(arr.length/index); i++) {
  currentPosition+=index
  result.splice(currentPosition + i, 0, 'cat')
}

console.log(result)

Upvotes: 2

Shashidhara P
Shashidhara P

Reputation: 1

You can use while loop to achieve it.

Flash Code Link

function showResult()
{
  var array = ["hello", "nice", "stack", "hi", "question", "random"];
  var pos = 2;
  var interval = 3;

  while (pos < array.length)
  {
    array.splice(pos, 0, 'cat');
    pos += interval;
  }

  document.getElementById("result").innerText = array;
}

Upvotes: 0

dave
dave

Reputation: 64725

I would implement an arrayChunk function, and then just do flatMap((el) => el.concat('cat'))

function arrayChunk(arr, size) {
    const R = [];
    for (let i = 0; i < arr.length; i += size) {
        R.push(arr.slice(i, i + size));
    }
    return R;
}


console.log(
    arrayChunk(["hello", "nice", "stack", "hi", "question", "random"], 2)
    .flatMap(el => el.concat('cat'))
)

Upvotes: 3

Related Questions