0

Ok so basically we have 2 arrays like this

Array1=[1, 3, 5, 7]
Array2=[0, 2, 4, 6]

and i want to unite them into one array like

Array3=[0, 1, 2, 3, 4, 5, 6, 7]

is there an algoithm for that? Or like a built in function? I mean i tried it but couldnt make it

Krysslk
  • 1
  • 3
  • Please visit [help], take [tour] to see what and [ask]. Do some research, [search for related topics on SO](https://www.google.com/search?q=javascript+merge+two+numeric+arrays+in+sorted+order+site:stackoverflow.com); if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Apr 18 '21 at 10:18
  • 1
    Consider reading up on mergesort. It's a pretty useful algorithm that does exactly what you're looking for. – Rumaisa Habib Apr 18 '21 at 10:39

2 Answers2

1

You can merge the two using .flatMap() on one of your arrays, and grabbing the associated value from your other array using the index:

const arr1 = [1, 3, 5, 7];
const arr2 = [0, 2, 4, 6];

const res = arr2.flatMap((num, i) => [num, arr1[i]]);
console.log(res);
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
0

I could not easily find one that retained order.

If you do not care for order then there are many, many dupes

Here is a reduce that works well

Note: start with the array with the lowest value in position 0

const Array1 = [1, 3, 5, 7];
const Array2 = [0, 2, 4, 6];

const Array3 = Array2.reduce((acc,arr,i) => (acc.push(arr,Array1[i]),acc),[]); 

console.log(Array3);
mplungjan
  • 134,906
  • 25
  • 152
  • 209