How do you sort an array without mutating it in JavaScript?
Copy the array first with spread, then sort: const sorted = [...arr].sort((a, b) => a - b). sort mutates in place, so you need a copy to preserve the original.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in map, filter, and reduce Best Practices in JavaScript
Always return from callbacks, do not mutate the original, use forEach for side effects, always pass an initial value to reduce, use find/some/every for early exit, use a comparator with sort, keep callbacks small, and avoid the map(parseInt) trap.
Because find stops at the first match (early exit), while filter iterates the entire array. find is faster for large arrays when you only need one element. It also signals intent: you want one, not all.
Do not pass parseInt directly to map. map passes (element, index, array), and parseInt takes (string, radix), so the index becomes the radix. Use .map(s => parseInt(s, 10)) or .map(Number) instead.
Still have questions?
Browse all our FAQs or reach out to our support team
