Kỹ thuật unique sort: loại bỏ phần tử trùng lặp và sắp xếp mảng cùng lúc.
Ví dụ
const arr = [1, 1, 1, 3, 2, 2, 8, 3, 4]; const uniqSort = (arr = []) => { const map = {}; const res = []; for (let i = 0; i < arr.length; i++) { if (!map[arr[i]]) { map[arr[i]] = true; res.push(arr[i]); }; }; return res.sort((a, b) => a − b); }; console.log(uniqSort(arr));
Kết quả
[ 1, 2, 3, 4, 8 ]