개발 기술/사소하지만 놓치기 쉬운 개발 지식

[JS] 원본을 바꾸지 않는 Array 메소드 (feat. TC39 3단계)

by GicoMomg (Lux) 2022. 6. 7.

🙂 JS의 ECMAScript 표준은 TC39위원회에 의해 결정된다. 이번 시간에는 TC39에서 3단계(ECMA-262 표준에 편입하고자하여 명세가 거의 마무리 된 상태)에 도달한 Array 메소드에 대해 알아보았다! (TC39제안서 보기)

해당 메소드는 포스팅 시점에는 표준화되지 않았지만 이 기술이 추가될 가능성이 높으므로 미리 알아두자!


1. toReversed()

  • reverse()는 배열의 순서를 반대로 뒤집어준다.
  • 단, reverse()를 사용하면 원본 배열도 변경되는 특징이 있다.
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.reverse();

console.log(arr);          // [5, 4, 3, 2, 1]
console.log(reversedArr);  // [5, 4, 3, 2, 1]  

🙂 원본을 변경하지 않고 배열을 뒤집을 수 없을까? toReversed()를 쓰자!

const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.toReversed();

console.log(arr);          // [1, 2, 3, 4, 5]
console.log(reversedArr);  // [5, 4, 3, 2, 1]  



2. toSorted()

  • sort(compareFn)compareFn에 따라 배열을 정렬한다.
  • 단, sort(compareFn)를 사용하면 원본 배열에도 영향을 준다.
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.sort((a,b) => b - a);

console.log(arr);          // [5, 4, 3, 2, 1]
console.log(reversedArr);  // [5, 4, 3, 2, 1]  

🙂 원본을 변경하지 않고 배열을 정렬할 수 없을까? toSorted(compareFn)를 쓰자!

const arr = [1, 2, 3, 4, 5];
const sortedArr = arr.toSorted((a,b) => b - a);

console.log(arr);          // [1, 2, 3, 4, 5]
console.log(sortedArr);    // [5, 4, 3, 2, 1]  



3. toSpliced()

  • splice()를 사용하면 배열에서 특정 요소를 삭제하거나 교체 혹은 새 요소를 추가할 수 있다.
  • 단, 원본 배열도 함께 변경되는 특징이 있다.
const arr = [1, 2, 3, 4, 5];

// 새 요소 추가
arr.splice(1, 0, 'new1');
console.log(arr);         // [1, "new1", 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];

// 기존 요소 교체
arr.splice(3, 1, 'new2');
console.log(arr);         // [1, 2, 3, "new2", 5]

🙂 원본을 변경하지 않고 요소를 추가하거나 교체할 수 없을까? toSpliced()를 쓰자!

const arr = [1, 2, 3, 4, 5];
const newArr = arr.toSpliced(1, 0, 'new1');

console.log(arr);         // [1, 2, 3, 4, 5];
console.log(newArr);      // [1, "new1", 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const newArr = arr.splice(3, 1, 'new2');

console.log(arr);         // [1, 2, 3, 4, 5];
console.log(newArr);      // [1, 2, 3, "new2", 5]



4. with(idx, value)

  • with(idx, value)는 배열의 idx에 value값을 할당할 수 있는데, 기존 array[idx] = value와의 차이점은 원본 배열에 영향을 주지 않는다는 점이다.
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(1, 'new1');

console.log(arr);         // [1, 2, 3, 4, 5];
console.log(newArr);      // [1, "new1", 2, 3, 4, 5]

반응형

댓글