DEV Community

Discussion on: Merging Arrays in Javascript

Collapse
 
ethan profile image
Ethan Stewart

This is a great way to think through and implement the algorithm for solving this problem. This is my take on a simpler, more compact solution using the ES6 spread operator and the built-in sort method on JS arrays:

function mergeLists(firstList, secondList) {
  return [...firstList, ...secondList].sort();
}

If you can't use ES6 for whatever reason, the concat method would allow you to still keep this nice and simple:

function mergeLists(firstList, secondList) {
  return firstList.concat(secondList).sort();
}
Collapse
 
janjuks profile image
janjuks • Edited

sort() should be sort((a, b) => a - b)
Otherwise, surprise, surprise - [1, 2, 11].sort() -> [1, 11, 2]

Collapse
 
ethan profile image
Ethan Stewart

I forgot about that, good catch!

Collapse
 
bengreenberg profile image
Ben Greenberg

Those are very compact, love the simplicity of it! My goal in these posts is to breakdown what's happening behind the scenes a bit so I intentionally spell out the steps rather than using a built in method. The idea being that once someone has some idea what's happening "behind the scenes" then they will more fully appreciate a language's built in methods.