Stop mutating caller data in `unique`
easy
unique(arr) look clever with a one-liner. The returned values seem close, but two subtle bugs slipped in: it reorders the data and it mutates the caller's array in place. Fix it so the helper keeps the first-seen order and does not change any shared input state.Solution idea
export default function unique(arr){
// Set already preserves first-seen order, so there is no need to sort.
return Array.from(new Set(arr.slice()));
}
Examples
const ids = [2,2,1,3,1];
const out = unique(ids);
// out: [2,1,3]
// ids must still be [2,2,1,3,1]
const state = { selectedIds: [3,3,2,1] };
unique(state.selectedIds);
// state.selectedIds must still be [3,3,2,1]Solution
Overview
export default function unique(arr){
// Set already preserves first-seen order, so there is no need to sort.
return Array.from(new Set(arr.slice()));
}
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.