How can I insert each of an arrays elements every other element in another array?

Viewed 571

I have two arrays.

let a = [1, 3, 5, 7] let b = [2, 4, 6, 8]

I want the result: a = [1, 2, 3, 4, 5, 6, 7, 8]

How can I insert each of array B's elements every other element in array A?

I have tried using splice in a for loop, but the length of array A changes so I cannot get it to work.

8 Answers

You can create a new array, loop through a and push the current item and the item in b at the same index:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = []
a.forEach((e,i) => res.push(e, b[i]))

console.log(res)

Alternatively, you can use Array.map and Array.flat:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = a.map((e,i) => [e, b[i]]).flat()

console.log(res)

If the arrays have the same length, then you can use flat map to avoid mutating the original array.

const a = [1, 3, 5, 7];
const b = [2, 4, 6, 8];

const res = b.flatMap((elem, index) => [a[index], elem]);

console.log(res);

You can try:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b]

console.log(newArray) // [1, 3, 5, 7, 2, 4, 6, 8]

If you want to sort just

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b].sort((a, b) => a - b)

console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8]

Create a new array and flatten it by doing the below.

let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
console.log(a.map((e, i)=> [e, b[i]]).flat());

Don't splice, just create a new array and push them in on every other index.

Do a for loop, and on each loop do newArrary.push(a[i]); newArrary.push(b[i]);

You can use reduce

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];

let c = a.reduce((acc, x, i) => acc.concat([x, b[i]]), []);

console.log(c)

This works for arrays of any length, adapt the code based on the desired result for arrays that are not the same length.

You could transpose the data and get a flat array.

const
    transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
    a = [1, 3, 5, 7],
    b = [2, 4, 6, 8],
    result = [a, b]
        .reduce(transpose, [])
        .flat();

console.log(result);

Related