查找必须添加数组开头的元素数才能获得总数超过 10 个的元素

  • 本文关键字:元素 开头 数组 查找 添加 javascript
  • 更新时间 :
  • 英文 :


>我有一个带数字的数组。需要查找数组开头必须添加多少个元素才能得到总共 10 个以上的元素。在代码中,我必须使用reduce

设 arr = [2, 3, 1, 0, 4, 5, 4];

在这种情况下,控制台必须显示数字 6。

我的代码不起作用:

let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {
let ourSum = 0;
while (ourSum <= 10) {
return sum + elem;
}
index++

}, 0)
console.log(sumNumber);

您可以找到索引并添加一个索引。

如果比较为真,则此迭代将停止。

let array = [2, 3, 1, 0, 4, 5, 4],
index = array.find((sum => value => (sum += value) > 10)(0));
console.log(index + 1);

let arr = [2, 3, 1, 0, 4, 5, 4];
// i is to store the element count at which it gets greater than 10
let i=0;
let sumNumber = arr.reduce((sum, elem, index) => {
// Checks if sum is greater than 10 yet?
if(sum>=10){
// this condn below will only evaluate once when for the
// first time the sum is greater than or equal to 10
if(i===0) i=index+1;
}
// updates the sum for every loop run
return sum+elem;
});
console.log("Element count for which sum is greater than equal to 10 is:",i);

这是一个解决方案:

const arr = [2, 3, 1, 0, 4, 5, 4]
const sumNumber = arr.reduce(
(acc, cur, index) => {
if (typeof acc === 'number') { // If the accumulator is a number...
return acc // Just return it
}
const sum = acc.sum + cur
if (sum > 10) { // If sum is greater than 10...
return index + 1 // ...return a number
}
return { sum } // Return an object with sum with the new value
},
{ sum: 0 } // Start with an object with the `sum` property of 0
)
console.log(sumNumber)

您可以使用some方法执行此操作,在达到条件时不必遍历其余元素。

var arr = [2, 3, 1, 0, 4, 5, 4];
var obj = {sum : 0, index : 0 };
arr.some((k,i)=>{
obj.sum+=k;
if(obj.sum > 10) {
obj.index = i+1;
return true
}
});
console.log(obj)

相关内容

最新更新