Stop mutating caller data in unique
uniqueeasy
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.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]Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- Taro: Capital One senior web front end engineer interview, 2023
One case round in this account went through badly written code and suggested refactorings. This drill practises rewriting a clever helper that mutates its input; it is not the reported code.
Reported in a public Capital One interview account. Capital One frontend interview questions
Solution
1
The fixed code
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.