如何找到多少项需要求和以获得数组javascript中的给定和



我有一个数组

var array = [4,2,6,8,1,6,5,2];
var samNeeded = 20;

如上所述,我需要得到从数组开始需要求和的项数,以得到所需的sum

需要输出的示例

var output = [4,2,6,8] 

作为前四项需要加起来得到总数20

不确定这是最好的方法,但它适用于您的示例:

const array = [4,2,6,8,1,6,5,2];
const samNeeded = 20;
let sum = 0;
const result = [];
// as long as array still has items and we haven't reached the target sum…
while (array.length && sum < samNeeded) {
result.push(array.shift()); // consume the next item of the input array
sum += result[result.length - 1]; // add it to sum as we go.
}
// it's not clear from your question whether you need the number of items…
console.log(result.length);
// or the items themselves:
console.log(result);

我的解决方案是:

const array = [4, 2, 6, 8, 1, 6, 5, 2];
const sumNeeded = 20;
let auxSum = 0;
const res = [];
for (let i = 0; i < array.length; i++) {
if (auxSum >= sumNeeded) break;
auxSum += array[i];
res.push(array[i]);
}
console.log(res);

您可以使用Array#reduce

var array = [4,2,6,8,1,6,5,2];
var sumNeeded = 20;
let [res] = array.reduce(([res, sum],curr)=>
[res.concat(sum >= sumNeeded ? []: curr), sum + (sum >= sumNeeded ? 0: curr)],
[[], 0]);
console.log(res);

最新更新