카테고리 없음
ES14
stella0905
2023. 10. 27. 16:25
toSorted
const arr1 = [3,1,2,5,4]
const arr2 = [...arr1]
console.log(arr1,arr2)
// [3,1,2,5,4],[3,1,2,5,4]
2개의 배열이 있다고 가정을 했을때 sort()와 toSorted()를 사용해서 정렬을 해준다.
const arr1Sorted = arr1.sort();
const arr2Sorted = arr2.toSorted();
console.log(arr1Sorted,arr2Sorted)
// [1,2,3,4,5],[1,2,3,4,5]
둘다 잘 정렬되는걸 볼 수 있다. 여기서 push(6)을 해준다면?
arr1Sorted.push(6)
arr2Sorted.push(6)
console.log(arr1Sorted,arr2Sorted)
// [1,2,3,4,5,6],[1,2,3,4,5,6]
정상적으로 정렬된 배열끝에 6이 들어가는걸 볼 수 있다.
근데 여기서 원본배열을 보게되면 값이 다른걸 보게된다.
console.log(arr1,arr2)
// [1,2,3,4,5,6],[3,1,2,5,4]
sort()를 해줬던 arr1배열은 원본배열을 훼손하기 때문에 정렬해주고 6을 추가한 1,2,3,4,5,6이 들어가있는데
원본배열을 훼손하지 않은 toSorted를 해준 arr2배열은 처음 값이였던 3,1,2,5,4가 들어있는걸 확인할 수 있다.
toReversed
toSorted와 동일하다!
arr1 = [3,1,4,5,2]
arr2 = [...arr1]
arr1Reversed = arr1.reverse()
arr2Reversed = arr2.toReversed()
arr1Reversed.push(6)
arr2Reversed.push(6)
console.log(arr1Reversed,arr2Reversed)
//[2,4,5,1,3,6],[2,4,5,1,3,6]
console.log(arr1,arr2)
//[2,4,5,1,3,6],[3,1,4,5,2]
toSpliced
const arr1 = [0,1,2,3,4,5,6,7,8]
const arr2 = [...arr1]
arr1.splice(4,3,'A','B','C')
console.log(arr1)
//[0, 1, 2, 3, 'A', 'B', 'C', 7, 8]
const arr3 = arr2.toSpliced(4,3)
const arr4 = arr2.toSpliced(4,3,'A','B','C')
console.log(arr3,arr4)
// [0, 1, 2, 3, 7, 8],[0, 1, 2, 3, 'A', 'B', 'C', 7, 8]
뒤에서부터 찾는 메서드
findLast = 주어진 조건에 해당하는, 뒤에서부터 첫 요소 반환
findLastIndex = 위 요소의 인덱스 반환
1. 앞에서 부터 찾는 메서드
const myArr = [1,2,3,4,5,6,7,8,9,10]
// 앞에서부터 찾는 메서드
const firstMult3 = myArr.fined(i => i % 3 === 0) // 3의배수중 맨앞에 숫자
const firstMult3Idx = myArr.finedIndex(i => i % 3 === 0)
console.log(firstMult3,firstMult3Idx)
// 3, 2
2. 뒤에서 부터 찾는 메서드
const myArr = [1,2,3,4,5,6,7,8,9,10]
const firstMult3 = myArr.findLast(i => i % 3 === 0) // 3의배수중 맨앞에 숫자
const firstMult3Idx = myArr.findLstIndex(i => i % 3 === 0)
console.log(firstMult3,firstMult3Idx)
// 9, 8
부분적으로 수정한 배열을 반환
- 첫 번째 인자로 주어진 인덱스의 값을 두 번쨰 인자로 주어진 값으로 수정한 새 배열 반환
orgArr = [1,2,3,4,5,6,7,8]
const newArr = orgArr.with(3, '넷')
console.log(newArr, orgArr)