자주 쓰이는 Array Methods 정리
toString()
const fruits = ['apple', 'banana', 'orange'];
const fruitStr = fruits.toString()
console.log(fruitStr)
.split()
- 문자열을 배열로 바꾸는 구분이 되는 기호를 ()에 넣음
const fruits = '🍎, 🥝, 🍌, 🍒';
const fruitStr = fruits.split(',')
console.log(fruitStr)
.reverse()
const array = [1, 2, 3, 4, 5];
const arrayRerese = array.reverse()
console.log(arrayRerese)
.splice()
- 배열을 맨 앞에서 부터 n개를 뺀 나머지로 새로운 배열을 생성
const array = [1, 2, 3, 4, 5];
const arrayDel = array.splice(2)
console.log(arrayDel) // [3, 4, 5]
다음 Array Methods를 쉽게 정리하기 위한 변수
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()
- find Method에 students안에 있는 배열 중 score: 90인 값을 콜백함수를 통해 조건에 맞는 첫번째 요소 값을 찾기
const result = students.find((student) => student.score === 90);
console.log(result)
.filter()
const result = students.filter((student) => student.enrolled === false)
console.log(result)
.map()
- 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출하여 새로운 배열로 만듬.
const result = students.map((students) => students.score)
console.log(result);
.every()
- 배열 안의 모든 요소가 주어진 판별 함수를 통과하는 지 확인하여 하나라도 아닐경우 false로 출력
const result = students.every((students) => students.score < 60)
console.log(result);
.reduce()
- 모든 요소를 돌면서 return 하여 누적되는 결과 값을 출력하여 평균값을 구할때 활용
const result = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(result / students.length);
Methods 활용
- 학생들의 점수를 오른차순인 문자열로 출력하고 싶은 경우
.map
을 이용하여 배열로 점수를 출력하고 .sort
를 이용하여 정렬하고 .join
으로 문자열으로 변환하는 식으로 활용이 가능합니다.
const result = students.map((students) => students.score).sort().join()
console.log(result);