[JavaScript] 12가지 유용한 배열 함수 - Array APIs

Array method

Posted by dongjune on January 6, 2021

join

join 함수는 배열의 모든 요소들을 string 하나로 합쳐줍니다.

1
2
3
const fruits = ["apple", "banana", "orange", 1];
const result = fruits.join("");
console.log(result); // 출력 : applebananaorange1

split

split 함수는 인자로 separator를 받아서 separator를 기준으로 문자열을 나눠 Array로 바꿔줍니다.

다음은 문자열을 콤마를 기준으로 분리하여 Array로 리턴해주는 코드입니다.

1
2
3
4
const fruits = "🍎, 🥝, 🍌, 🍒";
const result = fruits.split(",");

console.log(result); // ["🍎", " 🥝", " 🍌", " 🍒"]

reverse

reverse 함수는 이름 그대로, Array의 요소들을 거꾸로 뒤집은 새로운 배열을 리턴해줍니다.

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

console.log(array.reverse()); // [5, 4, 3, 2, 1]

slice

slice 함수는 배열을 특정 인덱스 부터 특정 인덱스까지 잘라줍니다.

slice 는 인자로 시작 인덱스와 끝 인덱스를 받아서 잘라주는데 이때 끝 인덱스는 포함하지 않고 잘라줍니다. 즉 인자로 받은 끝 인덱스의 직전 인덱스까지만 잘라서 return 해줍니다.

만약 시작 인덱스만 인자로 넣어주고 끝 인덱스의 인자를 넣어주지 않는다면 slice는 자동으로 첫 인덱스부터 마지막 인덱스까지의 배열을 리턴해줍니다.

또한 시작 인덱스와 끝 인덱스를 둘 다 넣어주지 않는다면 slice 함수는 그냥 배열 전체를 return 해줍니다.

다음에 살펴 볼 splice 함수와는 달리 원본배열을 변경하지 않고 추출만 해줍니다.

다음의 코드를 통해 확인해봅시다.

1
2
3
4
5
6
7
8
9
const array = [1, 2, 3, 4, 5];

console.log(array.slice()); // [1, 2, 3, 4, 5]

const newArr1 = array.slice(2);
console.log(newArr1); // [3, 4, 5]

const newArr2 = array.slice(1, 3);
console.log(newArr2); // [2, 3]

splice

첫번째 인자는 시작 인덱스이고 두번째 인자는 배열에서 제거할 요소의 개수입니다.
만약 제거할 요소의 개수를 인자로 넣어주지 않으면 자동으로 시작인덱스의 원소부터 가장 마지막 원소까지를 삭제해줍니다. 위에서 살펴본 slice 함수와는 달리 원본배열 자체를 수정합니다. return 값은 제거한 요소들의 배열입니다.

1
2
3
4
5
6
7
const array = [1, 2, 3, 4, 5];

const newArr = array.splice(0,2);
console.log(newArr); // [1, 2]

// 원본배열이 변경됨
console.log(array); // [3, 4, 5]

지금부터 나오는 배열 함수들은 다음의 Student 클래스 배열을 다루며 설명하겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student("A", 29, true, 45),
  new Student("B", 28, false, 80),
  new Student("C", 30, true, 90),
  new Student("D", 40, false, 66),
  new Student("E", 18, true, 88),
];

find

콜백 함수를 인자로 받아서 모든 요소마다 콜백 함수를 실행해줍니다.

요소를 순차적으로 돌면서 콜백 함수가 true를 리턴하는 첫 요소를 바로 리턴해줍니다.

다음은 학생의 점수가 90점인 요소를 찾는 코드입니다.

1
2
3
const result = students.find((student) => student.score === 90);

console.log(result); // Student {name: "C", age: 30, enrolled: true, score: 90}

filter

find 함수가 하나의 요소만 찾아줬다면 filter는 콜백 함수의 조건을 만족하는 모든 요소를 찾아서 새로운 배열을 return 해주는 함수입니다.

다음은 학생의 enrolled가 true인 모든 학생들을 찾아주는 코드입니다. enrolled가 true인 A, C, E 학생을 성공적으로 return 해줍니다.

1
2
3
const result = students.filter((student) => student.enrolled === true);

console.log(result); // [Student(A), Student(C), Student(E)]

map

map 함수는 말 그대로 배열의 요소들을 새롭게 맵핑해주는 함수입니다. 콜백 함수를 인자로 받아서 모든 요소마다 콜백 함수를 실행해주며 요소를 새롭게 맵핑해줍니다. 새롭게 맵핑 된 요소로 이루어진 새로운 배열을 리턴해줍니다.

다음의 코드에서처럼 map을 사용하면, Student 클래스로 이루어진 students 배열의 점수만 추출하여 점수만으로 이루어진 새로운 배열을 얻을 수 있습니다.

1
2
3
const result = students.map((student) => student.score);

console.log(result); // [45, 80, 90, 66, 88]

forEach

forEach 함수는 콜백함수를 인자로 받아서 모든 요소마다 콜백 함수를 실행해줍니다. map과 조금 유사하지만 map과는 달리 새로운 배열을 return 하지 않습니다. foreach는 그냥 콜백함수를 실행해주는 역할을 합니다.

1
2
const result = students.forEach((student)=>console.log(student.score));
// 출력 : 45 80 90 66 88

some

some 함수 역시 콜백 함수를 인자로 받습니다. 만약 콜백 함수의 조건을 만족하는 원소가 하나라도 존재한다면 바로 true를 return 해줍니다.

1
2
3
const result = students.some((student) => student.score < 50);

console.log(result); // true

every

every 함수는 some 함수와 반대로 모든 원소들이 콜백 함수의 조건을 만족해야 true를 return 합니다.

다음의 코드에서 every 함수는, 모든 원소들의 점수가 40 이상이므로 true를 return합니다.

1
2
3
const result = students.every((student) => student.score > 40);

console.log(result); // true

reduce

학생들의 점수의 평균을 구하려고 합니다. 평균을 구하기 위해서는 전체 점수의 합을 구해야 하는데 이 때 reduce 함수를 이용하면 좀 더 간편합니다.

reduce 함수는 콜백함수와 초기값을 인자로 받습니다. 특이하게 콜백함수의 인자로 이전 값과 현재 값을 받는데 이전 값은 이전의 원소가 콜백함수로 return 해준 값입니다.

따라서, 콜백함수에서 이전 값에 현재 값의 점수를 더한 값을 return 해준다면 다음 원소로 계속해서 누적 합을 return 해줄 것이고, 마지막 원소에서는 전체의 합을 return해줄것입니다.

다음은 reduce를 이용하여 전체 학생 점수의 평균값을 구하는 코드입니다.

1
2
3
4
5
6
7
const sum = students.reduce((prev, curr) => {
  return prev + curr.score;
}, 0);

const result = sum / students.length;

console.log(result); // 73.8