Array.prototype.sort() sắp xếp tại chỗ (in-place), không tạo bản sao. Đặc tính này đôi khi gây rắc rối.
Ví dụ: giữ nguyên mảng names, tạo mảng mới sắp xếp theo chữ cái.
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = names; sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
Vì mảng là đối tượng, gán bằng tham chiếu nên sắp xếp một mảng làm cả hai thay đổi.
Giải pháp
1. Dùng slice() khi khởi tạo mảng mới
Ví dụ
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = names.slice(); sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
slice() trả về bản sao nông (shallow copy). Cách này chưa tối ưu, chỉ hiệu quả với mảng chuỗi/số.
2. Dùng JSON.stringify() / JSON.parse()
Ví dụ
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = JSON.parse(JSON.stringify(names)); sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
Chuyển mảng thành chuỗi JSON và ngược lại buộc trình biên dịch không sao chép bằng tham chiếu.
Kết quả
Đầu ra cho cả hai cách:
[ 'Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj' ] [ 'Anshul', 'Dheeraj', 'Mukesh', 'Rakesh', 'Ram' ]