DEV Community

Discussion on: Merging Arrays in Javascript

Collapse
 
elarcis profile image
Elarcis • Edited

You can also make use of ES6 to merge any number of lists in a single call:

function mergeArrays(base, ...arrays) { 
  return base
    .concat(...arrays)
    .sort((a, b) => a - b);
}

Please mind that when using Array.prototype.sort without argument, the sorting is done via Unicode endpoints – pretty much an alphabetical sort, which means that this array:

[1, 8, 11, 10]

will be sorted into this one:

[1, 10, 11, 8]