The question is incomplete. The complete question is:
Write syntactically correct Javascript code to sort an array of sub-arrays containing integers using the sort and reduce array functions as described below. You will sort the sub-arrays in ascending order by the maxium value found in each sub-array. Your solution would be executed in the following manner:
var x = [ [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;
x.sort(compare);
will result in variable x containing [ 3 ] , [ 2, 5, 1], [ 22 , 16 , 8], [ 1 , 23 ] ]. The maximum value of each sub-array is shown here in bold. Your solution must be written so that when run with the code above, x will contain the sorted array.
Answer:
function compare(a , b) {
var max1 = Math.max(...a); //get the max in array a
var max2 = Math.max(...b); //get the max in array b
return max1 - max2;
}
var x = [ [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;
x.sort(compare);
Explanation:
Given an array A positive integers, sort the array in ascending order such that element in given subarray which start and end indexes are input in unsorted array stay unmoved and all other elements are sorted.
An array is a special kind of object. With the square brackets, access to a property arr[0] actually come from the object syntax. This is essentially the same as obj[key], where arr is the object, while numbers are used as keys.
Therefore, sorting sub-array in ascending order by the maxium value found in each sub-array is done:
function compare(a , b) {
var max1 = Math.max(...a); //get the max in array a
var max2 = Math.max(...b); //get the max in array b
return max1 - max2;
}
var x = [ [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;
x.sort(compare);