JavaScript method to merge and sort two arrays

Took 1 minutes 56 seconds to code JavaScript method to first merge two arrays and then return the sorted array. Here is the code snippet.

Code:

arr1 = [1, 5, 6, 2];
arr2 = [2, 8, 6, 5];
function merge(arr1, arr2) {
for (var i = 0; i < arr2.length; i++) {
arr1.push(arr2[i]);
}
}

merge(arr1, arr2); //changes arr1 unlike JavaScript concat() method

function sort(arr) {
for (var i = 0; i < arr.length; i++) {
for (var y = i + 1; y < arr.length; y++) {
if (arr[i] > arr[y]) {
k = arr[i];
arr[i] = arr[y];
arr[y] = k;
}
}
}
return arr;
}

document.write(sort(arr1));

Result:

1,2,2,5,5,6,6,8

No comments:

Post a Comment

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...