배열 함수

YOBY·2023년 10월 18일
0

push() 및 pop()

const fruits = ["apple", "banana"];
fruits.push("orange"); // ['apple', 'banana', 'orange']
const removedFruit = fruits.pop(); // 'orange', fruits: ['apple', 'banana']

push(): 배열의 끝에 'orange'를 추가합니다.
pop(): 배열의 끝에 있는 요소 'orange'를 제거하고 반환합니다.


unshift() 및 shift()

const fruits = ["apple", "banana"];
fruits.unshift("orange"); // ['orange', 'apple', 'banana']
const removedFruit = fruits.shift(); // 'orange', fruits: ['apple', 'banana']

unshift(): 배열의 앞에 'orange'를 추가합니다.
shift(): 배열의 맨 앞에 있는 요소 'orange'를 제거하고 반환합니다.


concat()

const fruits = ["apple", "banana"];
const vegetables = ["carrot", "spinach"];
const combined = fruits.concat(vegetables); // ['apple', 'banana', 'carrot', 'spinach']

concat(): 두 개 이상의 배열을 결합하여 새 배열을 생성합니다.


join()

const fruits = ["apple", "banana", "cherry"];
const result = fruits.join(", "); // 'apple, banana, cherry'

join(): 배열의 모든 요소를 문자열로 결합하고 지정된 구분자로 구분한 문자열을 반환합니다.


slice()

const fruits = ["apple", "banana", "cherry", "date"];
const sliced = fruits.slice(1, 3); // ['banana', 'cherry']
console.log(sliced); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date']

slice(): 배열의 일부분을 추출하여 새 배열을 생성합니다.


splice()

const fruits = ["apple", "banana", "cherry", "date", "fig"];
const deletedFruits = fruits.splice(2, 2, "grape", "kiwi");
console.log(deletedFruits); // ['cherry', 'date'] (삭제된 요소)
console.log(fruits); // ['apple', 'banana', 'grape', 'kiwi', 'fig'] (변경된 배열)

splice(): 배열의 특정 위치에서 요소를 추가, 삭제 또는 교체합니다.


forEach()

const numbers = [1, 2, 3];
numbers.forEach((number) => console.log(number)); // 1, 2, 3

forEach(): 배열의 각 요소에 대해 주어진 함수를 실행합니다. 반환값이 없습니다.


map()

const numbers = [1, 2, 3];
const doubled = numbers.map((number) => number * 2); // [2, 4, 6]

map(): 배열의 모든 요소에 대해 주어진 함수를 호출하고 그 결과로 새 배열을 생성합니다.


filter()

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => number % 2 === 0); // [2, 4]

filter(): 주어진 조건을 만족하는 모든 요소로 이루어진 배열을 반환합니다.


find()

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];
const user = users.find((user) => user.id === 2); // { id: 2, name: 'Bob' }

find(): 주어진 조건에 맞는 첫 번째 요소를 반환합니다.


findIndex()

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];
const userIndex = users.findIndex((user) => user.id === 2); // 1

findIndex(): 주어진 조건에 맞는 첫 번째 요소의 인덱스를 반환합니다.


reduce()

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0
); // 15

reduce(): 배열 요소를 순회하면서 하나의 값(누적값)으로 축소시키는 데 사용됩니다.


sort()

const fruits = ['banana', 'apple', 'cherry'];
fruits.sort(); // ['apple', 'banana', 'cherry']

sort(): 배열의 요소를 정렬합니다. 기본적으로 문자열로 정렬되며, 숫자로 정렬하려면 정렬 함수를 제공해야 합니다.

0개의 댓글