3

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?

0

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

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

Comments

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)

Comments

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;
}

1 Comment

Just use the built-in snippet editor. No need to link to an external site just to make your code runnable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.