[JS] Javascript #8 Summary
Javascript #8 Summary
- 드림코딩 by 엘리: 자바스크립트 9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6)
Caution
강의를 듣고 제가 기억하기 쉽게 기록하여 변형된 내용이 있을 수 있습니다.
오류가 있거나 해당 글에 문제가 있을 경우 피드백 부탁드립니다.
Array APIs
Q1. make a string out of an array
const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join();
console.log(result); // apple,banana,orange (separator default value is ',')
Q2. make an array out of a string
const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(',');
console.log(result); // ['🍎', '🥝', '🍌', '🍒']
Q3. make this array look like this: [5, 4, 3, 2, 1]
const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result); // [5, 4, 3, 2, 1]
console.log(array); // [5, 4, 3, 2, 1] ==> array 원본 데이터도 변환됨
Q4. make new array without the first two elements
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 4+1); // slice(start?, end?)
console.log(result);
splice
는 원본 데이터 array 를 변환시키기 때문에 new array 를 생성하는 것이 아니다.
const result = array.splice(0, 2);
console.log(result); // [1, 2]
console.log(array); // [3, 4, 5]
Q5 ~ Q10
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
const result = students.find(student => student.score === 90);
console.log(result);
Q6. make an array of enrolled students
const result = students.filter(student => student.enrolled);
console.log(result);
Q7. make an array containing only the students’ scores
result should be: [45, 80, 90, 66, 88]
const result = students.map(student => student.score);
console.log(result);
Q8. check if there is a student with the score lower than 50
const result = students.some(student => student.score < 50);
console.log(result);
const result2 = !students.every(student => student.score >= 50);
console.log(result2);
Q9. compute students’ average score
const score_sum = students.reduce((prev, curr) => prev + curr.score, 0);
const score_avg = score_sum / students.length
console.log(score_avg);
Q10. make a string containing all the scores
result should be: ‘45, 80, 90, 66, 88’
const result = students
.map(student => student.score)
.join();
console.log(result);
Bonus! do Q10 sorted in ascending order
result should be: ‘45, 66, 80, 88, 90’
const result = students.map(student => student.score)
.sort((a, b) => a - b)
.join();
console.log(result);
Leave a comment