0

I am trying to merge and sort 2 arrays in numerical order.

function merge_arrays(a, b) {
    console.log( (a.concat(b)).sort().join(" ") );
}

This works fine with single digits in an array, but it doesn't sort numbers with double digits properly.

e.g.:

a: [2, 3, 7, 8, 8,]

b: [7, 8, 13]

will output as: 13 2 3 7 7 8 8 8

Am I missing something?

1
  • Actually, I figured it out, I was missing the sort option function inside the .sort() .sort(function(c,d){return c-d)} Commented Jan 16, 2014 at 5:39

3 Answers 3

5

Quoting from MDN:

The default sort order is lexicographic (not numeric).

Try this instead:

function merge_arrays(a, b) {
    console.log( (a.concat(b)).sort(function(a, b) { return a - b; }).join(" ") );
}
Sign up to request clarification or add additional context in comments.

Comments

0

http://www.w3schools.com/jsref/jsref_sort.asp

See that section Note: When numbers are sorted alphabetically, "40" comes before "5".

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

The function specifies whether the numbers should be sorted ascending or descending.

Meaning This

function numOrdA(a, b){ return (a-b); }

and your code :

a.concat(b)).sort(numOrdA).join(" ")

Comments

0

Try this:

c = a.concat(b)
c == [2,3,7,8,8,7,8,13]
c.sort() == [13,2,3,7,7,8,8,8]

This is because, when not provided with a comparison function, sort automatically converts the elements of the list it is sorting to strings. In string land "13" < "2".

Check out the sort documentation.

So what you probably want is something like this:

function compare_number(a,b) {
    return a - b;
}

a.concat(b).sort(compare_number);

And to fully answer your question:

a.concat(b).sort(compare_int).join(" ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.