웹개발자공부/Javascript
Javascript - splice를 활용한 배열 내 두 요소 위치 변경 함수 작성
박더그
2023. 2. 14. 03:43
Javascript의 splice를 활용하여 배열 내 두 요소의 위치를 맞바꾸는 함수를 작성해보았습니다.
- 배열 요소 위치 변경 함수 -
//i가 0인 요소, i가 2인 요소의 위치를 서로 변경
//원본 배열 생성
const sourceArray = [1, 2, 3, 4, 5];
const arrayModify = (firstElementIndex, secondElementIndex) => {
//원본 배열의 불변성 유지를 위해 새로운 배열 생성
const resultArray = [...sourceArray];
//새로운 배열을 splice를 통해 수정
resultArray.splice(firstElementIndex, 1, sourceArray[secondElementIndex]);
resultArray.splice(secondElementIndex, 1, sourceArray[firstElementIndex]);
return resultArray;
};
console.log('수정 전', sourceArray);
console.log('수정 후', arrayModify(0, 2));
상기 소스코드를 실행시키면 다음과 같은 결과를 확인 할 수 있습니다.