-2

There are two arrays:

a1 = [0, 2, 4, 6, 8];
a2 = [1, 3, 5, 7, 9];

How I get this:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

I wanna to use RxJs or else.

If the value isn‘t a number, like an Object.

 a1 = [A, C, E, G, I]; 
 a1 = [{'name': 'Lucy'}, {'name': 'Lily'}, {'name': 'Jerry'}, {'name': 'Tom'}, {'name': 'Smith'}]

 a2 = [B, D, F, H, J]; 
 a2 = [{'name': 'Jack'}, {'name': 'John'}, {'name': 'Anan'}, {'name': 'Bob'}, {'name': 'Dav'}]

 a = [A, B, C, D, E, F, G, H, I, J];
蒋建雨
  • 355
  • 1
  • 4
  • 17
  • `a1.concat(a2)` – Damien Flury Mar 31 '18 at 13:17
  • 1
    `a1.concat(a2).sort()` actually – davidluckystar Mar 31 '18 at 13:17
  • a1.concat(a2).sort(); – Roemer Mar 31 '18 at 13:18
  • WHile I was typing... ;) – Roemer Mar 31 '18 at 13:18
  • Do you want to sort by numeric value or lexicographically as strings? – user202729 Mar 31 '18 at 13:21
  • [Possible duplicate](https://stackoverflow.com/questions/31922223/how-to-merge-two-sorted-array-in-one-sorted-array-in-javascript-without-using-so/31922374). [Possible duplicate](https://stackoverflow.com/questions/42817212/merge-two-sorted-arrays-into-one). [Or](https://stackoverflow.com/questions/42531614/merge-two-arrays-and-sort-the-final-one/42531787#42531787) [this](https://stackoverflow.com/questions/43591403/what-is-faster-merge-2-sorted-arrays-into-a-sorted-array-w-o-duplicate-values). – user202729 Mar 31 '18 at 13:22
  • 1
    Why you vote -1? – 蒋建雨 Mar 31 '18 at 13:28
  • What do you mean by objects A B C D E? Post a valid example – mehulmpt Mar 31 '18 at 13:42
  • I downvoted because your original question could be solved by a quick search, and your edit fundamentally changed the question, rendering answers obsolete. It's very unclear what you mean now, as well. – jhpratt Mar 31 '18 at 13:55

3 Answers3

1
[...a1,...a2].sort((a,b) => a-b)

That's ES6 syntax.

mehulmpt
  • 15,861
  • 12
  • 48
  • 88
0

With concat() and sort()

a1 = [0, 2, 4, 6, 8];
a2 = [1, 3, 5, 7, 9];

a = a1.concat(a2).sort();

console.log(a)
Javier S
  • 379
  • 3
  • 13
0
  const result = [];

  for(var i = 0; i < arr1.length && i < arr2.length; i++)
    result.push(arr1[i], arr2[i]);

  result push(...arr1.slice(i), ...arr2.slice(i));

That merges two arrays (arr1, arr2) by taking one each.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151