JS-new array를 return하는 method와 그렇지 않은 method

뿌야·2023년 4월 9일
0

자바스크립트

목록 보기
16/24

코딩 테스트를 풀다 보니, array와 관련된 method 중 new array를 반환하는지, 안반환하는지 헷갈리는 부분이 있었다. 물론 그때그때 찾아봐도 되지만 한번 기억에 넣을겸 여기에 정리해본다.

먼저 새로운 array를 return하는 메소드는 다음과 같다.

  • concat() : 여러 array를 합친다
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);

console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]
  • filter() : 조건에 해당하는 array를 생성한다.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4, 6]

-map() : array의 각 element에 대해서 주어진 조건을 수행한다. forEach와는 다르게 새로운 array를 반환했었다.

-slice(): array에서 내가 원하는 index 부분을 잘라낼 수 있다.

const fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango'];
const slicedFruits = fruits.slice(1, 4);

console.log(slicedFruits); // Output: ['banana', 'orange', 'kiwi']

다음은 기존의 array를 modify하고, 새로운 array를 리턴하지 않는 메소드들이다.

-splice(): 특정 인덱스에서부터 특정 개수의 element를 제거하고 그 자리에 원하는 element를 집어넣을 수 있다.

-reverse(): 기존 array의 위치를 반대로 바꾼다.

-sort(): 기존 array를 원하는 조건대로 정렬한다.

const numbers = [4, 2, 5, 1, 3];
numbers.sort();
console.log(numbers); // Output: [1, 2, 3, 4, 5]

기본 디폴트는 ascending order로 정렬되며 아래와 같이 사용하면 descending order로 사용할 수도 있다.

const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [5, 4, 3, 2, 1]

-push(): 원하는 elements를 기존 array에 삽입할 수 있다.

-pop(): 가장 마지막 element 하나를 없앨 수 있다.

const arr = [1, 2, 3, 4, 5];

const lastElement = arr.pop();

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

-shift() : 가장 처음에 오는 element 하나를 없앨 수 있다.

-unshift(): concat()처럼 array의 맨 앞에 내가 원하는 element를 넣을 수 있지만 concat()과 다르게 새로운 array를 반환하지는 않는다.

-forEach(): array의 각 element에 대해 역할을 수행하지만 새로운 array를 반환하지는 않는다.

0개의 댓글