Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. I am getting output [27,27,39,1001] but the output should be [27,5,39,1001].
function largestOfFour(arr) {
// You can do this!
var largest=[];
var gr=0;
for(var i=0;i<arr.length;i++){
for(var j=0;j<=arr[i].length;j++){
if(arr[i][j]>gr){
gr=arr[i][j];
}
}
largest.push(gr);
}
return largest;
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. I am getting output [27,27,39,1001] but the output should be [27,5,39,1001].
function largestOfFour(arr) {
// You can do this!
var largest=[];
var gr=0;
for(var i=0;i<arr.length;i++){
for(var j=0;j<=arr[i].length;j++){
if(arr[i][j]>gr){
gr=arr[i][j];
}
}
largest.push(gr);
}
return largest;
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Share
Improve this question
asked Feb 16, 2016 at 6:27
Uzma KhanUzma Khan
1391 gold badge4 silver badges14 bronze badges
2
- 3 What is the question? – Pointy Commented Feb 16, 2016 at 6:29
- Divide the problem into smaller problems and solve each problem on its own: 1) find the max value of a single array (put this logic in a function) 2) iterate over elements of array and find max of each (call function from step 1) 3) build a new array from the results of step 2 4) return the resulting array from step 3 5) profit – knittl Commented Feb 10, 2023 at 17:43
11 Answers
Reset to default 3Your logic is quite not right. To point out the error, see below.
Iteration 1
->gr = 0
->27 > 0?
->gr = 27
->push gr(27)
Iteration 2
->gr = 27
-> 5 > 27?
->push gr(27)
Iteration 3
->gr = 27
->39 > 27?
->gr = 39
-push gr(39)
Iteration 4
->gr = 1001
->1001 > 39?
->gr = 1001
->push gr(1001)
Try Creating a function with an array parameter that gets the largest number in that parameter instead of declaring a new for loop.
Array.max = function( array ){
return Math.max.apply( Math, array );
};
You can try something like this:
var data = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var maxArr = data.map(function(item){
return Math.max.apply(null,item)
});
document.write(maxArr);
Explanation of your code:
function largestOfFour(arr) {
// You can do this!
var largest=[];
var gr=0;
for(var i=0;i<arr.length;i++){
for(var j=0;j<=arr[i].length;j++){
if(arr[i][j]>gr){
gr=arr[i][j];
}
}
largest.push(gr);
}
return largest;
}
var r = largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
document.write(r)
You code works file, but the issue is with var gr=0;
. This is initialized outside the for loop
, so its paring largest number of first array with second and since 27>5
is false, it is assigning 27 only.
function largestOfFour(arr) {
// You can do this!
var largest = [];
for (var i = 0; i < arr.length; i++) {
var gr = 0;
for (var j = 0; j <= arr[i].length; j++) {
if (arr[i][j] > gr) {
gr = arr[i][j];
}
}
largest.push(gr);
}
return largest;
}
var r = largestOfFour([
[13, 27, 18, 26],
[4, 5, 1, 3],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]);
document.write(r)
You need to reset this value of gr
for every iteration, hence, it should be initialized inside loop.
Your function is right but you need put var gr=0; inside first for loop:
function largestOfFour(arr) {
// You can do this!
var largest=[];
for(var i=0;i<arr.length;i++){
var gr=0;
for(var j=0;j<=arr[i].length;j++){
if(arr[i][j]>gr){
gr=arr[i][j];
}
}
largest.push(gr);
}
return largest;
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function largestOfFour(arr) {
var results = [];
for (var n in arr) {
var largestNumber = 0;
for (var num in arr[n]) {
if (arr[n][num] > largestNumber) {
largestNumber = arr[n][num];
}
}
results[n] = largestNumber;
}
return results;
}
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);
Even-though, it looks like a test question and not having a clear question. I am going to go ahead and help you out.
var arr = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var res = [];
arr.forEach(function(val, ix){
var sub = val;
var large = 0;
for(var i=0;i<sub.length;i++){
if(sub[i] > large){
large = sub[i];
}
}
res.push(large);
});
Fiddle: https://jsfiddle/jeremyrajan/hted9eg5/
if you look at the code, I am using forEach(https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) to loop through array and collect the subarray. And then running a for-loop through the elements to find the max number.
The only difference being that, I used forEach in my case to make things a bit prettier.
Hope that helps!
Here is a cleaner way to do it, but it's relatively slow if you care about fast.
function get_array_of_largest(rank2Array){
var newArray = [];
for (var i = 0; i < rank2Array.length; i ++){
newArray.push(rank2Array[i].slice().sort(function(a, b){return a < b;})[0]);
}
return newArray;
}
.slice()
copies a portion of an array. Since no arguments were given, it copies the whole thing.
.sort()
sorts an array according to a function. Given the function I've sorted using, it sorts the array in descending order (element 0 is thus the greatest).
The reason yours is not working is that you're not resetting gr
to 0 after you push the element.
function largestOfFour(arr) {
var newArr=[];
for(i=0;i<arr.length;i++){
var num=Math.max.apply(null,arr[i]);
newArr.push(num);
}
return newArr;
}
The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
function largestOfFour(arr) {
return arr.map(x => x.sort((a, b) => b - a)[0]);
}
Here is an answer that junior level like me might find easier to understand.
function largestOfFour(arr) {
// We need a way new array that would store the largest number as required.
let newArr = []
// We need a way to traverse through the subArrays
for (let i=0;i<arr.length; i++)
{
// We need to find max in each sub array and add to newArr
newArr.push(Math.max(...arr[i]))
}
console.log(newArr) // Check if its the answer we expect
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
In this case, map and reduce together as a solution can be used.
The array is mapped
Found the largest numbers in the mapped array lists with reduce function
function lgArry (arr) { return arr.map(function(sub){ return sub.reduce(function(a,b){ return a > b ? a : b; }) }) }
This of your input purely as a matrix.
Now, you can spread the rows of the matrix into a function that takes varargs. These functions capture the arguments into an array and send them into a reducer.
const
avg = (...arr) => arr.reduce((a, b) => a + b) / arr.length,
avgPerRow = (...matrix) => matrix.map(row => avg(...row)),
minPerRow = (...matrix) => matrix.map(row => Math.min(...row)),
maxPerRow = (...matrix) => matrix.map(row => Math.max(...row));
let matrix = [
[13, 27, 18, 26],
[4, 5, 1, 3],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
],
averageOfFour = avgPerRow(...matrix),
smallestOfFour = minPerRow(...matrix),
largestOfFour = maxPerRow(...matrix);
console.log(...smallestOfFour); // [ 13 , 1 , 32 , 1 ]
console.log(...averageOfFour); // [ 21 , 3.25 , 35.75 , 714.75 ]
console.log(...largestOfFour); // [ 27 , 5 , 39 , 1001 ]