0

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);
2
  • 3
    What made you think you can glue together two arrays with a comma and it would just work? The result of that is a string. Tossing this back into an Array makes an array with that string as the singular element. Sorting it has no effect. Commented Nov 26, 2014 at 19:33
  • 2
    Protip: google "javascript merge arrays" Commented Nov 26, 2014 at 19:34

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Concat the two together, then sort them in ascending order

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

Comments

1

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.

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.