1

I wanted to merge two arrays like you can fold 2 packs of cards - in ugly code with for loop and assuming same length so no if's for safety it would look like this:

const arr = [1,2,3];
const rra = [4,5,6];
const result = [];

for(let i=0; i<arr.length; i++){
  result.push(arr[i],rra[i]);
}

console.log(result); // Array(6) [ 1, 4, 2, 5, 3, 6 ]

I know there is something similar in String.raw() but it cuts off last element and returns a string, is there equivalent in array ?

String.raw({raw: [1,2,3]}, ...[4,5,6]); //"14253"
CptDolphin
  • 404
  • 7
  • 23
  • what is actually the question? [`String.raw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) is to work with template literals. – Nina Scholz Dec 29 '19 at 20:35
  • can I merge two arrays like with the for loop above but in 1 line with some built in method/function – CptDolphin Dec 29 '19 at 20:36

1 Answers1

1

You can use .flatMap() for this - This is the same as .map(), followed by .flat()

const arr = [1,2,3];
const rra = [4,5,6];

let newArray = arr.flatMap((ele, i) => [ele, rra[i]]);

console.log(newArray);
Shiny
  • 4,945
  • 3
  • 17
  • 33
  • 1
    sorry for late mark as good answer, just realised I can do that. And obviously great answer just what I was looking for back then – CptDolphin Jan 09 '20 at 15:59