2

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 Answers8

1

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)
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

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);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

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]
1

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());
Charlie Han
  • 106
  • 6
0

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

stackers
  • 2,701
  • 4
  • 34
  • 66
0

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Using forEach and pushing the current element and the relative element from the other array is an option

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

let c = [];
a.forEach((x, i) => {c.push(x, b[i])});

console.log(c);

More about forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Ran Turner
  • 14,906
  • 5
  • 47
  • 53