Finding largest number in each sub-array of a 2D array? Javascript - javascript

I'm trying to return the largest number in each of the sub-arrays - but this is returning the first two values of each sub-array. Seems pretty simple and yet I can't find where I go wrong.
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
newArr.push(maxVal)
}
}
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))
This code returns the following: [ 4, 5, 13, 27, 32, 35, 37, 39, 1000, 1001 ]. Where am I going wrong? I don't want to use .sort()

The problem is, you push a new value whenever a new max value is found and not deleting the previously pushed value from the current set, you need to store the maxVal until the end of the inner loop and push the value afterwards, so you only push one value for each array, which is actually the biggest one
Your function should look similar to this:
function largestOfFour (arr) {
let maxVal = 0;
let newArr = [];
for (i = 0; i < arr.length; i++) {
// reset maxVal, for new set of numbers
maxVal = 0;
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
// new largest number found
maxVal = arr[i][j];
}
}
// push highest number found in set
newArr.push(maxVal);
}
return newArr
}

I don't know whether this is allowed, but it will get you the result:
const arr=[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
console.log(arr.map(a=>Math.max(...a)))

I prefer #CarstenMassmann's answer; however, just so you can understand how your code was in error, but very close, see this edit to the original attempt.
That inner conditional doesn't find the max of the sub-array, if finds the interim max. Don't push to your results inside the condition, finish iterating the sub-array and then push the best interim max...
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
// don't push here. maxVal is just the max *for now*
}
}
newArr.push(maxVal) // push here
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))

Related

return the largest array between arrays

I am a beginner in Javascript and I should write a code to solve this problem: Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. and write this code can u tell me what is the problem him thnx:
function largestOfFour(arr) {
var pos = 0;
var max = 0;
var add = 0;
var sum = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (j === 4) {
sum[i] = add;
} else {
add = add + arr[i];
}
}
for (var i = 0; i < arr.length; i++) {
if (sum[i] > max) {
max = sum[i]
pos = i;
}
}
return arr[pos];
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
If you have no restrictions, you could take
Array#map for getting a new array with
Math.max for getting a maximum number and take
spread syntax ... for converting an array to parameters.
const largestOfFour = array => array.map(a => Math.max(...a));
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
For a more classic style, you could separate the functions, one for processing the outer array and one for getting a maximum value.
function max(array) {
var max = array[0];
for (let i = 1; i < array.length; i++) {
if (max < array[i]) max = array[i];
}
return max;
}
function largestOfFour(array) {
var result = [];
for (let a of array) result.push(max(a));
return result;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Returning a result after nesting for loops

I'm trying to figure out how to get the below code to push the biggestNumber variable to the largestNumbers variable so that the largest number in each sub-array of largestOfFour will be returned as an array of largestNumbers.
I see it mentally and thought that I was writing the code correctly. This is my thought process:
1) largestNumbers is set up as an empty array.
2) create a for loop that will pull each sub-array during a loop and store it as PulledSubArray.
3) I need to loop through the sub-array(pulled
SubArray) with a for loop.
4) biggestNumber variable is set-up to store the biggest number in the sub-array and an if statement is set-up to determine which number is the biggest and then push that number to the largestNumbers array.
5) break the inner for loop and then repeat steps for second sub-array.
Without giving the answer to the entire challenge, could you tell me what syntax or elements I'm missing to achieve my end result
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i > arr.length; i++){
var pulledSubArray = arr[i];
for (var n = 0; n > pulledSubArray.length; n++){
var biggestNumber = 0;
if (pulledSubArray[n] > biggestNumber){
biggestNumber = pulledSubArray[n];
} else if (pulledSubArray[n] < biggestNumber){
largestNumbers.push(biggestNumber);
break;
}
}
}
return largestNumbers;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
for (var i = 0; i > arr.length; i++){
^
Wrong condition
Your loop constructs are wrong. Correct them. A simple version of your function looks like (ECMAScript6)
const largestOfFour = (arr) => arr.map(el => Math.max(...el));
In case you want to stick to your thought
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i < arr.length; i++) { // Correct loop condition
var pulledSubArray = arr[i];
var biggestNumber = pulledSubArray[0];
for (var n = 1; n < pulledSubArray.length; n++) { // Correct loop condition
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
}
}
largestNumbers.push(biggestNumber); // Push biggest number outside the inner loop
}
return largestNumbers;
}
console.log(largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]));
Issue is with Code:
Logic:
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
} else if (pulledSubArray[n] < biggestNumber) {
largestNumbers.push(biggestNumber);
break;
}
For an array [4, 5, 1, 3], for second iteration, biggestNumber holds 4 and pulledSubArray[n] will hold 5. For this case, is you would push the value and break the loop. But you are not checking the entire array. So you will not get accurate result.
Loop condition:
for (var i = 0; i > arr.length; i++){
This will never enter the loop. It should be i < arr.length
Variable declaration:
for (var n = 0; n > pulledSubArray.length; n++) {
var biggestNumber = 0;
if (pulledSubArray[n] > biggestNumber) {
Variable should be declared outside the loop. You are currently setting its value to 0 in every iteration. So you will eventually get the last value as if (pulledSubArray[n] > biggestNumber) will always return true.
Updated Code:
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i < arr.length; i++) {
var pulledSubArray = arr[i];
var biggestNumber = 0;
for (var n = 0; n < pulledSubArray.length; n++) {
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
}
}
largestNumbers.push(biggestNumber)
}
return largestNumbers;
}
var list = largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]);
console.log(list)
If you want to get largest number in each sub array:
var data = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
function largestOfFour(data) {
return data.map(function(d) {
return Math.max.apply(null, d)
})
}
console.log(largestOfFour(data))
Or even shorter (es6):
let data = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
const largestOfFour = data => data.map(d => Math.max.apply(null, d))
console.log(largestOfFour(data))

largest no in array (js program) [duplicate]

This question already has answers here:
Creating an array consisting of the largest values of each sub-array does not work as expected
(4 answers)
Closed 6 years ago.
Return Largest Numbers in Arrays
//my code
function largestOfFour(arr) {
var largest=[];
for(var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++) {
if(arr[i][j] > largest){
largest[i]= arr[i][j];
}
}
}
return largest;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//exp o/p
[27,5,39,1001]
//i m getting
[5,13]
I would do it in this way.
var largest=[];
a = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
for(var i = 0; i < a.length; i++){
largest.push(a[i].sort(function(a, b){return b-a})[0])
}
console.log(largest);
if(arr[i][j]>largest)
should be
if(arr[i][j]>largest[i])
Initialize your array too with some MIN value like 0
function largestOfFour(arr) {
var largest=[];
for(var i = 0; i < arr.length; i++){
largest[i] = 0;
for (var j = 0; j < arr[i].length; j++) {
if(arr[i][j] > largest[i]){
largest[i]= arr[i][j];
}
}
}
return largest;
}

Get maximum values of a multidimensional array

I'm trying to find the maximum values of a multidimensional array.
Input:
[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
Result:
[5, 27, 39, 1001]
What I've tried:
var largestArr = [];
function largestOfFour(arr) {
for (var i = 0; i < arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j = 0; j < stop; j++) {
if (currentArr[0] > largest) {
largest = currentArr[0];
largestArr.push(largest);
largestArr.shift();
}
}
return largestArr;
}
}
largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]);
Can anyone help me understand why this isn't working?
The problem is here
if (currentArr[0]>largest){
largest = currentArr[0];
//
}
This should be done like below:
if (currentArr[j]>largest){
largest = currentArr[j];
//
}
Why this is wrong?
This is wrong because you always compare the first item of each array with the largest and not all the items in each array one after the other.
Furthermore, you have to make a few more corrections.
Specifficaly, there isn't any need to use the shift method. You have only to push the largest value of each array after the end of each processing in the largestArr. Last, but not least you have to move the return statement of the largestArr out of the for loops.
var largestArr = [];
function largestOfFour(arr) {
for (var i=0; i<arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j=0; j<stop; j++){
if (currentArr[j]>largest){
largest = currentArr[j];
}
}
largestArr.push(largest);
}
return largestArr;
}
alert(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
Since the answer has been provided here's some code can do the same job in a smaller number of lines that you might find useful in the future using reduce.
var out = arr.reduce(function (p, c) {
return p.concat(Math.max.apply(null, c));
}, []);
DEMO
Christos' answer is correct and should the selected as answer.
Additionally though, you should not pollute the global namespace by declaring largestArray outside of the function, considering that you are returning said array anyway.
function largestOfFour(arr) {
var largestArr = []; // put this line here instead of making it global
for (var i=0; i<arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j=0; j<stop; j++){
if (currentArr[j]>largest){
largest = currentArr[0];
}
}
largestArr.push(largest);
}
return largestArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Search An Array Consisting of Sub-Arrays For the Largest Number and Return in a New Array

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]
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));
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);
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]], "");
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 ); };
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]]);
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]]);
#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;
}
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]
]);
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]]);

Categories

Resources