I'm going through some basic array challenges on w3.
Here is the task given:
Write a JavaScript program to sort the items of an array.
Sample array : var arr1 = [ 3, 8, 7, 6, 5, -4, 3, 2, 1 ]; Sample Output : -4,-3,1,2,3,5,6,7,8
Here is their given solution:
var arr1=[-3,8,7,6,5,-4,3,2,1];
var arr2=[];
var min=arr1[0];
var pos;
max=arr1[0];
for (i=0; i<arr1.length; i++)
{
if (max<arr1[i]) max=arr1[i];
}
for (var i=0;i<arr1.length;i++)
{
for (var j=0;j<arr1.length;j++)
{
if (arr1[j]!="x")
{
if (min>arr1[j])
{
min=arr1[j];
pos=j;
}
}
}
arr2[i]=min;
arr1[pos]="x";
min=max;
}
alert(arr2);
This is what I came up with... :
var arr1 = [ -3, 8, 7, 6, 5, -4, 3, 2, 1 ];
arr1.sort(function(a, b){return a-b});
console.log(arr1);
Why does it seem to me that their solution is so much more "convoluted"? Is it necessary to add their solution to protect against a specific use case?