const f = (ar, n, q) => {
if (n >= ar.length)
return `${n} is more than ${ar.length}`;
const sorted = ar.sort((a, b) => a - b);
do {
sorted.pop()
}
while (sorted.reduce((acc, each) => acc + each) > q);
return sorted;
}
//eg
const result = f([10, 4, 13, 11, 2], 4, 20);
You are
pop()
ing items from the array withoutpush()
ing them back. Shouldn't the result contain all the elements of the original array?ah. good point