배열에서 사용하는 map()
과 filter()
를 알아보자.
map()
class Car {
constructor(name, wheels, color, charge) {
this.name = name;
this.wheels = wheels;
this.color = color;
this.charge = charge;
}
}
const cars = [
new Car("bmw", 4, "black", false),
new Car("audi", 4, "white", false),
new Car("tesla", 4, "yellow", true),
]
// 참과 거짓을 배열로 나타낸다.
const result1 = cars.map((car) => car.wheels > 3);
const result2 = cars.map((car) => car.name === "bmw");
// 조건에 맞는 값을 배열에 담아낸다.
const result3 = cars.map((car) => car.color);
console.log(result1); // 결과: [ true, true, true ]
console.log(result2); // 결과: [ true, false, false ]
console.log(result3); // 결과: [ 'black', 'white', 'yellow' ]
filter()
true
인 값인 원소들로만 나열된 새로운 배열을 반환한다.class Car {
constructor(name, wheels, color, charge) {
this.name = name;
this.wheels = wheels;
this.color = color;
this.charge = charge;
}
}
const cars = [
new Car("bmw", 4, "black", false),
new Car("audi", 4, "white", false),
new Car("tesla", 4, "yellow", true),
]
// 결과 값이 참으로 구성된 배열을 반환하는 것을 볼 수 있다.
const result4 = cars.filter((car) => car.charge);
const result5 = cars.filter((car) => car.name === "bmw");
console.log(result4); // 결과: [ Car { name: 'tesla', wheels: 4, color: 'yellow', charge: true } ]
console.log(result5); // 결과: [ Car { name: 'bmw', wheels: 4, color: 'black', charge: false } ]
자바스크립트로 코딩테스트 문제를 푸는 과정에서 for loop를 자주 이용하곤 했었는데 다양한 배열관련된 메서드로도 문제를 풀어나가봐야겠다.