1

So I've been fighting with this a few hours now- the goal is to create a new array of the highest numbers in each array of 4. However, I can't seem to get it to loop more than once. How am I screwing up this for loop?

function largestOfFour(arr) {
 for (var i = 0; i < arr.length; i++) {
 var allTop = ""; 
 var top = arr[i].sort(function(a, b) {
 return b - a; 
 });
 i++;
 allTop.push(top[0]);
 }
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

takendarkk
3,4578 gold badges27 silver badges38 bronze badges
asked Mar 28, 2018 at 20:23
1
  • Your snippet does not work at all allTop.push is not a function. Commented Mar 28, 2018 at 21:02

4 Answers 4

3

The variable allTop should be defined before the loop as an array, and returned after the loop ends:

function largestOfFour(arr) {
 var allTop = [];
 
 for (var i = 0; i < arr.length; i++) {
 var top = arr[i].sort(function(a, b) {
 return b - a;
 });
 allTop.push(top[0]);
 }
 
 return allTop;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

answered Mar 28, 2018 at 20:26

1 Comment

Ahhhhhh a scope problem. Mostly. Thank you!
3

A better approach is using the function map along with the function Math.max

function largestOfFour(arr) {
 return arr.map(function(a) {
 return Math.max.apply(null, a);
 });
}
var result = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);

Full ES6:

var largestOfFour = (arr) => arr.map(a => Math.max(...a));
var result = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);

answered Mar 28, 2018 at 20:25

1 Comment

This is very similar to the other approach I was trying- thank you for demonstrating how Math.max and map can work together
2

Try this:

function largestOfFour(arr) {
 let allTop = [];
 arr.forEach(a => {
 allTop.push(Math.max.apply(Math, a));
 });
 return allTop;
}
console.log(
 largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])
);
answered Mar 28, 2018 at 20:34

Comments

1

Other solution would be to use function reduce along with the function Math.max

function largestOfFour(arr) {
 return arr.reduce((a, x) => {
 a.push(Math.max.apply(null,x));
 return a;
 }, []);
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

answered Mar 28, 2018 at 20:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.