배열에 대해 알아보았으니 이제 배열에 쓰이는 배열함수들을 살펴보자...!
toString 메소드는 지정된 배열 및 그 요소를 문자열로 반환한다.
const fruits = ['apple', 'banana', 'orange'];
let listOfFruit = fruits.toString();
console.log(listOfFruit); //"apple,banana,orange"
split 메소드는 string들을 split하여 새로운 배열을 만들어낸다.
const fruits = '🍎, 🥝, 🍌, 🍒';
let array = fruits.split(",");
console.log(array) //["🍎", " 🥝", " 🍌", " 🍒"]
배열의 요소 순서를 반전시킨다. 해당 메소드는 원 배열의 순서도 반전시키기에 사용에 유의해야한다!
const array = [1, 2, 3, 4, 5];
const reversedArray = array.reverse<();
console.log(reversedArray); //[5, 4, 3, 2, 1]
console.log(array); //[5, 4, 3, 2, 1] 원 배열도 바꾼다.
배열의 일부를 추출한 새 배열을 반환(return)한다.
arr.slice([begin[, end]])
begin은 추출 시작점에 대한 인덱스를, end는 추출을 종료할 인덱스를 의미한다.
만약 end인덱스를 생략하면 begin인덱스부터 마지막 인덱스까지를 return한다.
이는 원배열을 바꾸지 않는다.
const array = [1, 2, 3, 4, 5];
const arrayCopy = array.slice(2);
console.log(arrayCopy); //[3, 4, 5]
//splice는 원배열을 바꾸기 때문에 여기서는 사용할 수 없다.
console.log(array) //[1, 2, 3, 4, 5]
그렇다면 아래의 배열 예시를 통해 좀더 심화된 메소드들을 살펴보자.
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),
];
주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다. 만약 해당하는 요소가 없으면 undefined
를 반환한다.
구문: arr.find(callback[, thisArg])
const result = students.find((student) => student.score === 90);
console.log(result); //Student {name: "C", age: 30, enrolled: true, score: 90}
주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다.
const enrolledStudents = students.filter((student) => student.enrolled);
console.log(enrolledStudents); //[Student, Student, Student]
배열 내 모든 요소 각각에 대해 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
const studentScores = students.map((student) => student.score);
console.log(studentScores) //[45, 80, 90, 66, 88]
some
메소드는 배열 안의 한 요소라도 주어진 판별 함수를 통화하는지 테스트 하고, 그 결과값으로 true
, false
를 반환한다. every
는 반면 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트 한다.
빈 배열에서
some
은 무조건 false를,every
는 true를 return한다.
const check = students.some((student) => student.score < 50);
console.log(check<); //true
const check2 = !students.every((student) => student.score >= 50);
console.log(check2); //!를 사용해서 true를 출력한다.
배열의 각 요소에 대해 주어진 reducer함수를 실행하고, 하나의 결과값을 반환한다.(이름에서 알 수 있듯, 배열의 값을 줄여나가 하나의 값을 리턴한다.)
콜백함수는 네 인수를 받는다.
reduce()
함수 호출에서 initialValue
를 제공한 경우, accumulator
는 initialValue
와 같고, currentValue
는 배열의 0번 인덱스 값과 같다. initialValue
가 제공되지 않았다면, accumulator
는 배열의 0번 인덱스 값과 같고, currentValue
는 배열의 1번 인덱스 값과 같다. const result = students.reduce((pre,cur)=> pre + cur.score, 0)
console.log(result / students.length); //73.8
참고 링크: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
배열의 모든 요소를 연결하여 하나의 문자열로 합친다.
const scoreString = students
.map((student) => student.score)
// .filter(score => score >= 50) 50점 이상인 아이들만 뽑고 싶다면..!
.join();
console.log(scoreString); //"45,80,90,66,88"
sort는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환한다.
const scoreOrder = students.map((student) => student.score)
.sort((a, b) => a - b)
// .sort((a, b) => b - a); //내림차순으로 정렬하고 싶을때
console.log(scoreOrder); //[ 45, 66, 80, 88, 90 ]