Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  95] [ 6]  / answers: 1 / hits: 5295  / 9 Years ago, wed, november 25, 2015, 12:00:00

I want to extract the largest number of every single array. I believe it should be possible with the .map function.



This is what I have so far, but unfortunately this returns [ undefined, undefined, undefined, undefined ]



Code:



function largestOfFour(largestOfFour) {
largestOfFour.forEach(function(number){
number.sort(function(a, b){
return b - a;
});
highestValue = number.map(function(number){
return number[0];
});
});
};

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

More From » arrays

 Answers
4

You're iterating over the outer array,



function largestOfFour(largestOfFour) {
largestOfFour.forEach(function(number){


and then sorting the inner arrays,



number.sort(function(a, b){
return b - a;
});


and then of those inner arrays you're trying to acquire the [0] property from each value, which is undefined



highestValue = number.map(function(number){
// you redefine `number` here to be the value within the inner array
return number[0];
});


What you probably want to do is map the outer array:



function largestOfFour(largestOfFour) {
largestOfFour.map(function(numbers){


sort the inner arrays:



numbers.sort(function(a, b){
return b - a;
});


and then return the first value:



return numbers[0];





All together it probably should be:



function largestOfFour(largestOfFour) {
return largestOfFour.map(function(numbers){
numbers.sort(function(a, b){
return b - a;
});
return numbers[0];
});
}


Although there are simpler ways to find the maximum values of an array of arrays.



One such example is to use Array.prototype.reduce:



function largestValues(outer) {
return outer.map(function (inner) {
return inner.reduce(function (prev, current) {
return Math.max(prev, current);
}, Number.NEGATIVE_INFINITY);
});
}

[#32621] Tuesday, November 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbie

Total Points: 262
Total Questions: 91
Total Answers: 102

Location: Bermuda
Member since Mon, Dec 5, 2022
1 Year ago
;