// Q1. make a string out of an array
{
const fruits = ["apple", "banana", "orange"];
const fruitsString = fruits.join();
console.log(fruitsString); // apple,banana,orange
}
// Q2. make an array out of a string
{
const fruits = "🍎, 🥝, 🍌, 🍒";
const fruitsArray = fruits.split(",", 3);
// 두번째 인자로 리턴받을 사이즈 지정
console.log(fruitsArray); // ["🍎", " 🥝", " 🍌"]
}
// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
const array = [1, 2, 3, 4, 5];
const reversed = array.reverse();
console.log(reversed); // [5, 4, 3, 2, 1]
}
// Q4. make new array without the first two elements
{
const array = [1, 2, 3, 4, 5];
const sliced = array.slice(2, 5);
console.log(sliced); // [3, 4, 5]
console.log(array); // [1, 2, 3, 4, 5]
// splice는 원배열까지 건드리므로 원배열을 보존하고 싶을 땐 slice를 사용
const spliced = array.splice(0, 2);
console.log(spliced); // [1, 2]
console.log(array); // [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),
];
// Q5. find a student with the score 90
console.log(students.find((student) => student.score === 90));
// Q6. make an array of enrolled students
const enrolled = students.filter((student) => student.enrolled);
console.log(enrolled);
// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
console.log(students.map((student) => student.score));
// Q8. check if there is a student with the score lower than 50
console.log(students.some((student) => student.score < 50));
// Q9. compute students' average score
const result = students.reduce((prev, curr) => prev + curr.score, 0);
console.log(result / students.length); // 73.8
아래와 같이 함수로 그룹핑하여 프로그래밍 하는 것을 함수형 프로그래밍이라고 함.
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
console.log(students.map((student) => student.score).join());
// 위 결과에서 filter 기능을 추가했을 경우
console.log(
students
.map((student) => student.score)
.filter((score) => score >= 50)
.join()
);
// Q11. do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
console.log(
students
.map((student) => student.score)
.sort((a, b) => a - b)
.join()
);