Home > OS >  How to combine two arrays differently in JS [closed]
How to combine two arrays differently in JS [closed]

Time:09-16

For example, let a = [1, 2, 3, 4] and b = [5, 6, 7, 8].

On concating b into a will result in c = [1, 2, 3, 4, 5, 6, 7, 8].

I want to combine in such a way that the resulting array c = [1, 5, 2, 6, 3, 7, 4, 8].

The arrays will be of same length. How do I do it in javascript?

Note: Looking to use a built-in function instead of a for-loop

1) Loop over the array a, and push the number in the result array.

If both have same length then you can use reduce

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

const result = a.reduce((acc, num, i) => {
  acc.push(num, b[i]);
  return acc;
}, []);

console.log(result);

2) Using flatMap

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

const result = a.flatMap((n, i) => [n, b[i]]);

console.log(result);

3) Using for..of loop in js

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

const result = [];
const itr = b[Symbol.iterator]();

for (let val of a) {
  result.push(val, itr.next().value);
}

console.log(result);

CodePudding user response:

If the two arrays are of the same length, you could use a for loop or map

const newArr = [];
for(let i = 0; i < a.length; i  ) { 
  newArr.push(a[i]); //] symbol was missing
  newArr.push(b[i]);
}

CodePudding user response:

Concat => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Or using ES6 array spread => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

  • Related