user1863593
user1863593

Reputation: 199

Javascript - sort issue

I am attempting to sort an array that is not working correctly. No errors, just the output is displaying as: [10,5,12,15,38,45,16,1,6,5,2,25]. Please give me an idea of the issue with my sort code.Thanks

var arr1 = [10, 5, 12, 15, 38, 45, 16];
var arr2 = [1, 6, 5, 2, 25];
var arr3 = merge(arr1, arr2);

function merge(arr1, arr2) {

    var combine = arr1 + "," + arr2;

    var arr3 = new Array(combine);

    for (var i = 0; i < arr3.length; i++) {

        arr3.sort(function (n1, n2) {
           return n1-n2;
        });
    }
       document.writeln("Array 3 sorted: " + arr3);

       return arr3;
  }

  merge(arr1, arr2);

Upvotes: 0

Views: 53

Answers (3)

Barmar
Barmar

Reputation: 780994

Your problem isn't with sorting, it's with combining the two input arrays into arr3.

var combine = arr1 + "," + arr2;

creates a single string that contains all the elements of arr1 and arr2 separated by commas. Then

var arr3 = new Array(combine);

creates an array with only 1 element, that string. You could use:

var arr3 = combine.split(',');

But it would be better to use the proper function for appending arrays in the first place:

var arr3 = arr1.concat(arr2);

See the MDN documentation

Upvotes: 3

justinpinili
justinpinili

Reputation: 894

you should be using .concat() instead of combining the two arrays with a comma. Combining the two arrays with a comma will result in a string.

solution: var arr3 = arr1.concat(arr2);

then you can call .sort() on arr3.

Upvotes: 1

Travis J
Travis J

Reputation: 82287

Concat the two together, then sort them in ascending order

var arr3 = (arr1.concat(arr2)).sort(function(a,b){return a-b;});

Upvotes: 1

Related Questions