[JS] Array methods

Chaewon Yoon (Jamie)·2023년 9월 6일
0

[Today I learned]

목록 보기
32/32

forEach(): 배열에서 for문을 대체해서 사용됨

callback함수의 여러 가지 매개변수를 통해 다양한 기능을 수행함

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

arr.forEach((elm, idx, array) => {
console.log(`${idx}번째 요소는 ${elm}입니다.`);
console.log(array);
})

// 0번째 요소는 1입니다.
// [1, 2, 3, 4, 5]
// ...

첫 번째 매개변수: 요소
두 번째 매개변수: index
세 번째 매개변수: 배열 요소의 수만큼 동일한 배열을 출력

map(): 배열 안의 모든 원소를 변환해서 새로운 배열로 돌려줌

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

let newArray = arr.map((elm) => {
return elm * 10;
});

console.log(newArray);

// [10, 20, 30, 40, 50]

1. 요소
2. index
3. array

at(): 배열의 맨마지막 값을 확인할 때

let colors = ["green", "blue", "purple"];

console.log(colors.at(1));
// blue

console.log(colors.at(-1));
// purple

includes(): 매개변수로 받은 요소를 배열이 판별하고 있는지 판별하여 boolean으로 반환

let colors = ["green", "blue", "purple"];

console.log(colors.includes("blue"));
// true

console.log(colors.includes("blue", 2));
// false 두 번째 값부터 blue가 있는지 검사

console.log(colors.includes("blue", 1));
// true 첫 번째 값부터 blue가 있는지 검사

indexOf(): array에서 특정값을 가진 요소가 몇 번째에 위치하는지 index를 찾아줌

Object에서는 못 찾음

console.log(colors.indexOf("purple"));
// 2

colors.indexOf("blue", 1);
// 1

colors.indexOf("yellow");
// -1
배열에 존재하지 않는 값을 찾으려고 하면 -1을 반환함

findIndex(() => {}): 배열의 요소가 객체일 때 사용

array - indexOf()
object - findIndex()

let colors = [
{id: 1, color: "green"},
{id: 2, color: "blue"},
{id: 3, color: "purple"}
];

let idx = colors.findIndex((elm) => elm.color === "purple");

console.log(idx);
// 2

1. 요소
2. index
3. array

find(): 찾아낸 값 그 자체를 반환하는 함수

let idx = colors.find((elm) => elm.color === "purple");

console.log(idx);
// {id: 3, color: "purple"}

filter(): 특정 조건을 만족하는 값들만 따로 만들어 배열로 반환함

let filterArray = colors.filter((elm, idx, array) =>
elm.id > 1);

console.log(filterArray);

slice(): 배열에서 특정값들만 추출해 새로운 배열 생성

특정 배열에서 원하는 부분만 자르기

let colors = [
{id: 1, color: 'green'},
{id: 2, color: 'blue'},
{id: 3, color: 'purple'},
{id: 4, color: 'yellow'}
]

let sliceArray = colors.slice(1, 3);
console.log(sliceArray);
// id: 2, id: 3
begin부터 end-1 요소까지 새로운 배열로 반환
(index 1부터 3-1까지)

concat(): 두 개의 배열을 이어붙여 하나의 새로운 배열로 반환

let array1 = ["green", "blue"];
let array2 = ["purple", "yellow"];

array1.concat(array2);
// ["green", "blue", "purple", "yellow"];

join(): 하나의 배열 안에서 요소들의 값들을 문자열로 이어줌

사이에 어떤 문자를 넣을지 결정 (기본은 쉼표)

let array = ["green", "blue", "purple", "yellow"];

console.log(array.join());
// green,blue,purple,yellow
console.log(array.join(" "));
// green blue purple yellow

sort(): 오름차순 배열 정렬

let colors = ["green", "blue", "purple"];
colors.sort();

console.log(colors);
// ["blue", "green", "purple"]

내림차순으로 정렬하려면?

비교함수를 직접 만들어서 sort()에 전달해야 함

const compare = (a, b) => {
	if (a > b) return -1;
  else if (a < b) return 1;
  else return 0;
};
// a: 배열의 다음 요소, b: 배열의 이전 요소
// 0보다 작은 값(-1): a가 b보다 앞에 있어야 함 => 이전 요소와 다음 요소의 위치 변경
// 0보다 큰 값(1): b가 a보다 앞에 있어야 함
// 0: 순서 변경X

let colors = ["green", "blue", "purple"];
color.sort(compare);
// purple > green > blue

console.log(colors);
// ["purple", "green", "blue"]

숫자 정렬

let numbers = [1, 100, 25, 50, 120, 3];
numbers.sort();

console.log(numbers);
// [1, 100, 120, 25, 3, 50] 사전순 정렬

숫자 오름차순 정렬
다음 요소(a) - 이전 요소(b) < 0 : 순서 변경

const compare = (a, b) => {
  return a - b;
}
let numbers = [1, 100, 25, 50, 120, 3];
numbers.sort(compare);

console.log(numbers);
// [1, 3, 25, 50, 100, 120]

숫자 내림차순 정렬
다음 요소(a) - 이전 요소(b) > 0 : 순서 변경

const compare = (a, b) => {
  return b - a;
}
let numbers = [1, 100, 25, 50, 120, 3];
numbers.sort(compare);

console.log(numbers);
// [120, 100, 50, 25, 3, 1]

reduce(): 배열의 각 요소에 함수 실행 후 누적된 값 출력할 때

let numbers = [1, 100, 25, 50];
let sum = 0;

numbers.forEach((elm) => {
  sum += elm;
})

console.log(sum);
// 176
let numbers = [1, 100, 25, 50];
let sum = numbers.reduce((acc, cur, idx) => {
  console.log(acc, cur, idx);
  return acc + cur;
}, 0);	// 0: accumulator의 초기값(initial value)

// accumulator: callback함수의 반환값을 누적하는 매개변수
// current value: 현재 처리할 요소의 값
// current index: 현재 처리할 요소의 index

console.log(sum);
// 0 1 0
// 1 100 1
// 101 25 2
// 126 50 3
// 176

isArray(): 전달된 매개변수가 배열인지 아닌지 판별

코드를 짜다 보면 특정 변수가 담고 있는 값이 배열인지 객체인지 문자인지 숫자인지 헷갈릴 때 사용

let a = Array.isArray([1, 100, 50]);
let b = Array.isArray({id:1, color:"green"});
let c = Array.isArray("string");
let d = Array.isArray(undefined);

console.log(a, b, c, d);
// true
// false
// false
// false
profile
keep growing as a web developer!🧃

0개의 댓글