자바스크립트 Array.prototype 메서드 추가

김현태·2023년 5월 22일
1

js

목록 보기
1/3
post-thumbnail

자바스크립트의 메서드중에 불변성을 유지하지 못하는 메서드들이 많은데 이번에 추가로 불변성을 유지시켜주는 메서드가 추가되서 정리한번 해보았다.

  1. toSorted
const originSorted = [1,2,3,4,5];
const newSorted = originSorted.sort((a,b)=> b-a);
console.log(originSorted);//[5,4,3,2,1]
console.log(newSorted);//[5,4,3,2,1]
console.log(originSorted === newSorted);//true

기존의 sort메서드는 원본을 참조하여 변수에 원본 주소값을 넘겨주기에 불변성을 유지하지 못하였지만

const originToSorted = [1,2,3,4,5];
const newToSorted = originToSorted.toSorted((a,b)=> b-a);
console.log(originToSorted);//[5,4,3,2,1]
console.log(newToSorted);//[5,4,3,2,1]
console.log(originToSorted === newToSorted);//true

toSorted를 사용해주면 원본은 그대로 유지하되 newToSorted 변수에 새로운 배열을 반환해준다.


  1. toReverse()
const originReverse = [1,2,3,4,5];
const newReverse = originReverse.reverse();
console.log(originReverse);//[5,4,3,2,1];
console.log(newReverse);//[5,4,3,2,1]
console.log(originReverse === newReverse);//true
const originReverse = [1,2,3,4,5];
const newReverse = originReverse.toReverse();
console.log(originReverse);//[1,2,3,4,5]
console.log(newReverse);//[5,4,3,2,1]
console.log(originReverse === newReverse);//false

reverse()를 사용하면 원본 배열의 주소값을 반환하였지만 toReverse()메서드는 새로운 배열을 만들어 반환시켜주기에 기존 배열의 불변성을 유지할 수 있다.


  1. with(index, value)
const originWith = [1,2,3,4,5];
const newWith = originWith.with(3,100);
console.log(originWith);//[1,2,3,4,5]
console.log(newWith);//[1,2,3,100,5]
console.log(originWith === newWith);//false

with()메서드는 첫번째 인자값으로 인덱스를 받고 두번째 인자값으로 대체할 값을 받는다.
with(3,10)을 해석하자면 배열의 3번째 인덱스 값을 100으로 바꿔줘! 라는 뜻이다.
기존에는 slice를 사용하여 코드가독성이 떨어지는 측면이 있었는데 이를 해결해 준 느낌이다.

ex) [...array.slice(0,3), 바꿔줄 값, ...array.slice(4)]


  1. findLast()
const find = [1,2,3,4,5];
find.find((el) => console.log(el));//1,2,3,4,5

const findLast = [1,2,3,4,5];
findLast.findLast((el) => console.log(el))//5,4,3,2,1

기존의 find()는 배열 탐색 시 첫번째 인자부터 검색했지만 findLast()는 가장 마지막 인자부터 탐색을 시작한다. 비록 시간복잡도 측면에서는 비슷하지만 맨 뒤부터 검색해보고 싶다면 위 메서드를 사용할 수 있을것같다.


  1. findLastIndx()
const findIndex = [1,2,3,4,5];
findIndex.findIndex((_,idx) => console.log(idx))//0,1,2,3,4

const findLastIndex = [1,2,3,4,5];
findLastIndex.findLastIndex((_,idx) => console.log(idx))//4,3,2,1,0

findIndex()메서드는 배열 첫번째 인덱스부터 탐색을 시작하고, findLastIndex()는 배열 마지막 인덱스부터 탐색을 시작한다. 이 메서드도 배열 가장 마지막 인덱스부터 탐색을 하고 싶다면 사용해보길 바란다.

0개의 댓글