1

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?

5 Answers5

5

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
3

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'))
)
dave
  • 62,300
  • 5
  • 72
  • 93
2

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);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
2

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)
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
0

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;
}
  • Just use the built-in snippet editor. No need to link to an external site just to make your code runnable. – Wyck Jul 21 '21 at 17:58