可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.
function largestOfFour(arr) {
var one = arr[0];
var two = arr[1];
var three = arr[2];
var four = arr[3];
var newArr = [];
for (var i = 0; i < one.length; i++){
var oneLrg = 0;
if (one[i] > oneLrg){
oneLrg = one[i];
}
newArr.push(oneLrg);
}
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]
回答1:
Using >
:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
if(arr[i][j] > maximum) // Compare
maximum = arr[i][j]; // Update maximum
newArr.push(maximum); // Store the real maximum
}
Using Math.max
:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
maximum = Math.max(maximum, arr[i][j]); // Update maximum
newArr.push(maximum); // Store the real maximum
}
Adding apply
:
var newArr = [];
for(var i=0; i<arr.length; ++i) // Iterate array
newArr.push( // Store ...
Math.max.apply(Math, arr[i]) // ... the maximum of the subarray
);
Adding ECMAScript 5 map,
var newArr = arr.map(function(subarray) {
return Math.max.apply(Math, subarray);
});
Adding ECMAScript 5 bind,
var newArr = arr.map(Function.apply.bind(Math.max, Math));
Or adding ECMAScript 6 arrow functions and spread operator,
var newArr = arr.map(subarray => Math.max(...subarray));
回答2:
The problem here is that you're overwriting oneLrg
at each loop iteration, and pushing it inside the same loop, so you're comparing each value to 0 and then, as one[i]
is bigger, saving it.
Try this:
var oneLrg = 0;
for (var i = 0; i < one.length; i++){
if (one[i] > oneLrg){
oneLrg = one[i];
}
}
newArr.push(oneLrg);
回答3:
No doubt that @Austin Hansen and I are leveraging the same learning environment for this challenge: Free Code Camp.
Having just worked through this challenge myself (FCC calls them "Bonfires"), I figured I'd provide solution that heavily dovetails from @Oriol 's excellent ">" solution.
I've included a specific note about the code blocks because to us newbies (at FCC or elsewhere), the absence of such can give us fits for hours : )
function largestOfFour(arr) {
var finalArray = [];
for(i = 0; i < arr.length; i++) { // iterates through each array
var max = -Infinity;
for(j = 0; j < arr[i].length; j++) { // iterates through each sub-array
if(arr[i][j] > max) { // comparing each successive element within the sub-array to what is currently stored as max
max = arr[i][j]; //if the ">" comparison is true then max gets updated
}
}
finalArray.push(max); // ensure this is OUTside of the j for loop. putting it INside the j for loop returns a very long (and wrong) array. try it.
}
console.log(finalArray);
return finalArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
https://jsbin.com/puweci/edit?js,console
FCC recognizes the follow solution which doesn't NOT leverage Array.push().
function largestOfFour(arr) {
var results = [];
for (var i = 0; i < arr.length; i++) {
var max = -Infinity;
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
results[i] = max;
}
return results;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
回答4:
This function will take two numbers and return their maximum:
var greatest = function(a,b){ return Math.max(a,b); };
This function will take an array of numbers and apply the greatest
function to each number in turn (using the .reduce( callbackFunction, initialValue )
method of arrays) to get the maximum value in the array:
var findMaximum = function( arr ){ return arr.reduce( greatest, Number.NEGATIVE_INFINITY ); };
The findMaximum
function can be simplified by just calling Math.max()
with all the array values (eliminating the need for the greatest
function); like this:
var findMaximum = function( arr ){ return Math.max.apply( Math, arr ); };
This function will take an array (of arrays) and call findMaximum
on each element of it and return a new array containing those maximums (using the .map( callbackFunction )
method on an array):
var largestOfFour = function( arr ){ return arr.map( findMaximum ); };
回答5:
This post hasn't had any new updates in about 3 months, but I figured I would post my solution to this problem as it looks a bit different than most of the other solutions posted thus far. Figured someone might find it helpful!
I am using quite a few built in method functions( .forEach, .sort, .push, .shift) a quick google search will explain each of these fairly well if you are unsure of how they work. https://developer.mozilla.org is a great resource for these.
function largestOfFour(arr) {
var newArr = []; //set up new empty array
arr.forEach(function(subArr){ //iterate through array with .each function
subArr.sort(function(a, b){ //use .sort to place largest number of each subarray into index[0]
return a < b;
});
newArr.push(subArr.shift()); //use .push method to .shift the index[0] number to newArr
});
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
回答6:
You can have a look at this:
function largestOfFour(arr) {
var newArr=[];
largestnum=0;
for(i=0;i<arr.length;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]>largestnum)
largestnum=arr[i][j];
}
newArr.push(largestnum);
largestnum=0;
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
回答7:
@orion - Your answer to me was not working. If the push is inside the if statement was pushing numbers that were not suppose to be in the array. As a result the first would push [4,5] and wound't work. So I moved the push out of the for statement and reset the lgstNumber to 0 also after so it wouldn't use it for the next sub-array. This worked for me...
function largestOfFour(arr) {
// You can do this!
var newArr = [];
var lgstNumber = - Infinity;
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
if(lgstNumber < arr[i][j]){
lgstNumber = arr[i][j];
}
}
newArr.push(lgstNumber);
lgstNumber = 0;
}
return newArr;
}
回答8:
function largestOfFour(arr) {
return arr.map(function(subArray) {
return subArray.reduce(function(firstArray, secondArray) {
return firstArray > secondArray ? firstArray : secondArray;
});
});
}
largestOfFour([[13, 27, 18, 26],[4, 5, 1, 3],[32, 35, 37, 39],[1000, 1001, 857, 1]
]);
回答9:
its more efficient.
function largestOfFour(arr) {
for(var x=0;x<arr.length;x++)
{
for(var y=0;y<arr[x].length;y++)
{
arr[x]=arr[x].sort(function(a,b)
{
return b-a;
});
}
}
var array=[];
for(var a=0;a<arr.length;a++)
{
for(var b=0;b<arr[a].length;b++)
{
if(b==0)
{
array[a]=arr[a][b];
}
}
}
return array;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);