Fractional Knapsack Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Fractional Knapsack runs in O(n log n) time and O(1) space, in JavaScript as in every other language.
- ✓Array.prototype.sort is the only sort primitive - there is no separate stable/unstable variant to choose between the way several languages below force you to.
- ✓Always pass an explicit comparator, (a, b) => b.value / b.weight - a.value / a.weight - never rely on the no-argument form.
- ✓The JavaScript trap: Array.prototype.sort() with no comparator coerces every element to a string and compares UTF-16 code units, so [10, 9, 2].sort() returns [10, 2, 9], not the numeric order.
- ✓V8 has sorted every array with TimSort since V8 7.0 (Chrome 70 / Node 11) - before that, arrays over 10 elements used an unstable quicksort variant, so results now stay stable across engine versions but relying on stability in code that also has to run on an older runtime is not safe.
What Fractional Knapsack actually is
Fractional Knapsack in JavaScript: what you actually reach for
JavaScript implementation
function fractionalKnapsack(items, capacity) {
// spread first: sort() mutates its receiver, and the caller's array is not
// ours to reorder. TimSort since V8 7.0: guaranteed O(n log n), stable.
const byRatio = [...items].sort((a, b) => (b.value / b.weight) - (a.value / a.weight));
let totalValue = 0;
let remaining = capacity;
for (const item of byRatio) {
if (remaining <= 0) break;
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
const ratio = item.value / item.weight;
totalValue += ratio * remaining;
remaining = 0;
}
}
return totalValue;
}
// forgetting the comparator sorts lexicographically, not numerically
[10, 9, 2].sort(); // [10, 2, 9] - NOT [2, 9, 10]Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Fractional Knapsack?
Array.prototype.sort is the only sort primitive - there is no separate stable/unstable variant to choose between the way several languages below force you to. Array.prototype.reduce folds the sorted list into a total, and because every JS number is a float64, value / weight is always true division - no accidental integer truncation of the ratio the way a naive C-family implementation using int division could produce.
What is the most common JavaScript mistake when implementing Fractional Knapsack?
Array.prototype.sort() with no comparator coerces every element to a string and compares UTF-16 code units, so [10, 9, 2].sort() returns [10, 2, 9], not the numeric order. Forgetting the comparator on a ratio sort silently produces string order on 'ratio-looking' numbers instead of throwing, which is what makes this bug survive code review.
How does Fractional Knapsack actually perform in JavaScript?
V8 has sorted every array with TimSort since V8 7.0 (Chrome 70 / Node 11) - before that, arrays over 10 elements used an unstable quicksort variant, so results now stay stable across engine versions but relying on stability in code that also has to run on an older runtime is not safe. The comparator is a real JS function call per comparison; recomputing value / weight inside it on every comparison instead of precomputing a ratio once per item costs an extra division per comparison, not per element. Time complexity is O(n log n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.