function sortArray(array) {
const clone = array.slice();
clone[0].name = "hohoho";
clone.sort((a, b) => a.age - b.age);
return clone;
}
const data = [
{ name: "a", age: 30 },
{ name: "b", age: 10 },
{ name: "c", age: 20 }
];
const sorted = sortArray(data);
console.log(JSON.stringify(data));
console.log(JSON.stringify(sorted));
// [{"name":"hohoho","age":30},{"name":"b","age":10},{"name":"c","age":20}]
// [{"name":"b","age":10},{"name":"c","age":20},{"name":"hohoho","age":30}]
- 정렬은 배열 내부의 객체를 수정하거나 건드릴 일이 없기 때문에 slice로 배열에 대한 복사만 해도 된다.
- 그렇지만 복사한 배열이라도 내부 객체는 여전히 원본의 참조를 가지고 있기 때문에 조심하자.
immutable sort test