Knapsack algorithm in JavaScript - Integer weights and values
I don't think your algorithm actually works.

First...

while (totalWeight &lt; capacity) {


...is not the proper criteria for determining when loading into the knapsack should be completed.  What if the knapsack capacity is 10 and you got passed 4 objects each having weight of 3?   The most you could ever get in the knapsack is a weight of 9.  With your condition as is, you would get an infinite loop.

Second...

    totalValue += ratio;


...makes no sense.  Why are you adding the value/weight ratio to the total value summation?

Third...

    totalWeight++;


...also makes no sense. Why are you incrementing the total weight?

Probably something like the following is what you would need

function knapsack(items, capacity) {
    let totalValue = 0;
    let totalWeight = 0;
    let remainingItems = items.sort( (a, b) =&gt; {
        return (b.value / b.weight) - (a.value / a.weight);
    });
    while (remainingItems.length &gt; 0) {
        const remainingCapacity = capacity - totalWeight;
        remainingItems = remainingItems.filter( (item) =&gt; {
            return (item.weight &lt;= remainingCapacity);
        });
        if (remainingItems.length === 0) continue;
        const addedItem = remainingItems.shift();
        totalValue = totalValue + addedItem.value;
        totalWeight = totalWeight + addedItem.weight;
    }
    return totalValue.toFixed(2);
}


Note that this would work even with floats, however this does not validate input data against weight = 0 items which would cause error.  In production code, it might be needed to validate the item being passed against this (and possibly other things like negative values/weight, negative/zero capacity, etc.)