I would like to create sub arrays of [10,10,10,10,10,10,10,10,10,4,4,4] that sum of each sub array is not greater than 100, so the result should be [[10,10,10,10,10,10,10,10,10,4,4],[4]]
I tried below, but not work not sure where the problem is at
const arr=[10,10,10,10,10,10,10,10,10,4,4,4]
const result=[]
let sum=0
let temp=[]
for(let i=0; i<arr.length;i ){
if(sum arr[i]<=100){
sum =arr[i]
temp.push(arr[i])
}else{
result.push(temp)
sum=0
temp.length=0
temp.push(arr[i])
sum =arr[i]
}
}
console.log(result) //[ [ 4 ] ]
CodePudding user response:
After you push temp
onto result
you need to create a new temp
array, not set the length of the old array to 0
, because you have a reference to that array in result
. So change temp.length = 0
to temp = []
.
And at the end of the loop you need to push the final temp
onto result
.
const arr = [10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 4]
const result = []
let sum = 0
let temp = []
for (let i = 0; i < arr.length; i ) {
if (sum arr[i] <= 100) {
sum = arr[i]
temp.push(arr[i])
} else {
result.push(temp)
sum = 0
temp = []
temp.push(arr[i])
sum = arr[i]
}
}
if (temp.length > 0) {
result.push(temp);
}
console.log(result)
CodePudding user response:
First: don't use temp.length=0
Second: you're not creating a new array inside else
, so basically you're editing what you have pushed inside result
Inside else
, after pushing into result
, just use temp = []
On top of that, you shall check if there are additional items inside temp
and the end of the loop, and do one more push into result