week 3 | JavaScript TIL | 배열 method

설탕·2021년 12월 8일
0

slice: 배열 요소 추출

배열.slice(시작index, 끝index)

시작index부터 끝index 이전까지 추출하여 새 배열 반환.
기존 배열은 그대로 유지됨.

const arr = [0, 1, 2, 3, 4, 5];
console.log(
arr.slice(2), // [2, 3, 4, 5] (2부터 끝까지)
arr.slice(1, 4), //  [1, 2, 3] (1부터 3까지)
arr.slice(-2), // [4, 5] (끝에서부터 2개)
arr.slice(2, -1), // [2, 3, 4] (2부터 끝-1까지)
arr // [0, 1, 2, 3, 4, 5] (기존 배열 그대로)
);

splice: 배열 요소 부분 변경

배열.splice(index, 삭제개수, 요소1, 요소2, …)

index 위치에서 삭제개수만큼 삭제하고 요소1, 요소2, … 추가.
splice 자체는 삭제된 요소를 반환.
기존 배열은 유지되지 않음.

const fruit = ['딸기', '복숭아', '바나나', '메론'];
console.log(fruit.splice(2, 1, '망고', '사과')); // ['바나나']
console.log(fruit); // ['딸기', '복숭아', '망고', '사과', '메론']

const animal = ['사자', '곰', '토끼', '다람쥐'];
console.log(animal.splice(-2, 1)); // ['토끼']
console.log(animal); // ['사자', '곰', '다람쥐']

map: 배열 변환

배열.map(콜백함수)

콜백함수: (요소, index, 기존배열) => 변경 후 요소 *인수 생략 가능
배열 내 모든 요소에 대해 콜백함수를 실행한 결과를 모아 새 배열로 반환.
기존 배열은 그대로 유지됨.

const taste = ['딸기', '바나나', '초코'];
console.log(
taste.map((value) => value + '우유'), // ['딸기우유', '바나나우유', '초코우유']
taste.map((value, index) => index + 1 + value), // ['1딸기', '2바나나', '3초코']
taste // ['딸기', '바나나', '초코'] (기존 배열 그대로)
);

const arr = [2.5, 3.1, 4.7];
console.log(
arr.map(Math.round), // [3, 3, 5]
arr // [2.5, 3.1, 4.7] (기존 배열 그대로)
);

filter: 조건 만족하는 배열 요소 추출

배열.filter(콜백함수)

콜백함수: (요소, index, 기존배열) => 조건 *인수 생략 가능, 조건은 Boolean
배열의 각 요소에 대해 콜백함수를 실행했을 때, true를 반환하는 요소를 모아 새 배열로 반환.
기존 배열은 그대로 유지됨.

const arr = [1, 2, 3, 4, 5, 6];
console.log(
arr.filter((value) => value > 3), // [4, 5, 6]
arr.filter(function (value) {
    return value > 3
}), // [4, 5, 6]
arr // [1, 2, 3, 4, 5, 6] (기존 배열 유지)
);

concat: 배열 결합

배열1.concat(배열2, 배열3, …)

배열을 합쳐서 새 배열 반환.
기존 배열은 그대로 유지됨.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]

concat 이용해 두 배열의 합집합, 교집합, 차집합 구하기

indexOf 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환
includes 배열이 특정 요소를 포함하고 있는지 판별

const arr1 = ['빨강', '노랑', '초록', '보라'];
const arr2 = ['노랑', '파랑', '분홍', '보라'];

// arr1 + arr2
const sum = arr1.concat(arr2);
console.log(sum); // ['빨강', '노랑', '초록', '보라', '노랑', '파랑', '분홍', '보라']

// 합집합
const union = sum.filter((value, index) => sum.indexOf(value) === index);
console.log(union); // ['빨강', '노랑', '초록', '보라', '파랑', '분홍']

// 교집합
const intersec = sum.filter((value, index) => sum.indexOf(value) !== index)
console.log(intersec); // ['노랑', '보라']

// 차집합
const differ = union.filter((value) => !intersec.includes(value));
console.log(differ); // ['빨강', '초록', '파랑', '분홍']

참고 블로그

push, unshift: 배열 요소 추가

배열.push(요소1, 요소2, …) 배열 마지막 위치에 요소 추가
배열.unshift(요소1, 요소2, …) 배열 처음 위치에 요소 추가

pop, shift: 배열 요소 삭제

배열.pop(요소1, 요소2, …) 배열 마지막 위치의 요소 삭제
배열.shift(요소1, 요소2, …) 배열 처음 위치의 요소 삭제

profile
공부 기록

0개의 댓글