Return Largest Numbers in Arrays

Heggy Castaneda
Jul 25, 2017 · 3 min read

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

[Option 1] Set up: create a variable to return it to focus on our end result which is a sorted array.

code setup

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].



https://repl.it/Jgcv/2
arr.sort(compareFunction);// note that (b - a) orders descending order (largest to smallest)function compareFunction(a, b) {
return b - a;
}

[Option 2] solving it using forEach() to iterate

Review of forEach function. Start simple. Example: for each that logs out each number in an array.

[1,2,3].forEach(function (num){
console.log(num)
}); // 1,2,3

Now, combine .forEach()’s power with .sort().

var num = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];function test (num) {
num.forEach(function(item) {
item.sort(function(a,b) {
return b-a;
});
});
return num;
}
test(num); // output: [ [ 5, 4, 3, 1 ], [ 27, 26, 18, 13 ], [ 39, 37, 35, 32 ], [ 1001, 1000, 857, 1 ] ]

Use for loop to extract first index from each subarray.

// we have sub array inside of array
var num = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
// output array with subarr sort b-a (high - low)
function test (num) {
// for forEach with sort to work, array needs to be 2-D array
// since .sort already sorts 1-D array we are enhancing it by adding
// .forEach iterates main array then .sort iterates subarray
num.forEach(function(item) {
item.sort(function(a,b) {
return b-a;
});
});
var resultSortedArr = [];
for(var i = 0; i < num.length; i++) {
resultSortedArr[i] = num[i][0];
}
return resultSortedArr;
}
// debugger;
test(num);

[Option 3] FCC solution breakdown:

https://forum.freecodecamp.org/t/freecodecamp-algorithm-challenge-guide-return-largest-numbers-in-arrays/16042

Review on how to update array.

update array using assingment

I want to know if I could get to the subArray index [0] and create a result array.

https://repl.it/Jgcv/3

Now, finally add if statement to compare largest number.

https://repl.it/Jgcv/4

// output: [5, 27, 39, 1001]

Heggy Castaneda

Written by

like to build things

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade