Reputation: 87
*I have Boolean array *
var array=[[0 ,1 ,1 ,1],[0 ,0, 1, 1],[1 ,1 ,1 ,1],[0 ,0 ,0 ,0]]
how to find maximum-number of 1s I want to javascript solution Here is my aproch
var array = [
[0, 1, 1, 1],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]
]
var indexValue = 0
var count = 0
array.forEach(function(element, index) {
var value = element.reduce(function(a, b) {
return a + b
})
if (value > count) {
indexValue = index
}
})
console.log(indexValue)
This code is perfect but I want more optimization in my code
Upvotes: 0
Views: 70
Reputation: 862
This isnt any more optimized from what i can tell, however it is an alternate way to solve your problem if you prefer it.
var array = [
[0, 1, 1, 1],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]
]
var indexValue = 0
var best = 0
array.forEach(function(element, index) {
var val = element.filter(v => v == 1).length;
if(val > best){
best = val;
indexValue = index;
}
});
console.log(indexValue)
Upvotes: 0