Stop mutating caller data in `unique`

easy
By FrontendAtlas Editorial · Updated Oct 5, 2026
A teammate tried to make 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]