I have 4 arrays:
Note: Length of array length is different in any session
var Class_A = [8, 11, 3, 9, 11, 16, 16]; var Class_B = [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77]; // Greatest length with 11 items, var Class_C = [10, 14, 19]; var Class_D = [8, 2];
I need to select array with greatest number of items, (Class_B)
My expectation is:
var major = number major of array.length (in this case Class_B);
My code:
var major = max(Class_A.length > Class_B.length > Class_C.length > Class_D.length);
Edit An unorthodox solution, from a newbie but it works.
var Class_A = [8, 11, 3, 9, 11, 16, 54, 14, 5]; var Class_B = [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77, 16, 7]; // Greatest length with 11 items, var Class_C = [10, 14, 19]; var Class_D = [8, 2]; var Classes = []; Classes.push(Class_A.length) ; Classes.push(Class_B.length) ; Classes.push(Class_C.length) ; Classes.push(Class_D.length) ; console.log("Lenght of 4 arrays>"+Classes); Classes.sort(function(a, b) { // order by major number return a - b; }); Classes.reverse(); // reverse array console.log("Total>"+Classes); // print sort by major number console.log("Major>"+Classes[0]); // Works => the magic number that I need
Advertisement
Answer
Put all your arrays in an array.
classes = [Class_A, Class_B, Class_C, Class_D];
Then, to get the largest one:
classes.reduce((acc, curr) => curr.length > acc.length ? curr : acc); // => [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77]
EDIT:
Or, if you want length of the largest array:
classes.reduce((acc, curr) => curr.length > acc ? curr.length : acc, 0); // => 11