Here is my code, is there a possible way to get the element highest sum all i know is to summing up a 2d array. but what i want is get element whose has a highest value when you sum them up check my code
const sumof2dArray = (arr) => {
let newArr = []
for(let i = 0; i < arr.length;i++){
let sum = 0
console.log(arr[i])
for(let j = 0; j < arr[i].length;j++){
sum = sum + arr[i][j]
}
newArr.push(sum)
console.log(sum)
}
let max = newArr[0]
for(let i of newArr){
if(i > max){
max = i
}
}
return max
}
sumof2dArray([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]])
my output is: 44
but what i want is the element expected output should be: [1,3,40]
5
Answers
Use two variables, one to hold the highest sum, and another to hold the array that has that sum. Then loop through the 2D array, updating those variables whenever a row’s sum is higher than the max.
The 44 comes from when you write
But you are doing nothing with the return value of the function.
If you want it to output the return value, just replace
with
You can traverse all subarrays. USE two sub-variables, one to store the sub-array with the largest sum, the other to store the position of the sub-array with the largest sum
Here’s another method using
Array#reduce
.Here are a couple answers you can use.
I think the first is more intuitive, just keeping track of the max array at the same time as the max sum.
The second one is just using
reduce
inside ofreduce
to narrow down to the highest array.It can be helpful to initialize
max
to-infinity
in case you have negative values in your sub arrays. If they were all negative for example, you’d never find any summed array with a higher value than the initial max. That also allows you to then start a loop at the beginning of the array, and not have to treat the first element separately.Each of these examples only has to sum each sub array once.