JS 기초 강의(ES5+) - # Array Apis(9)

Minsoo·2021년 8월 20일
0

Array Apis 너무 어려워서 복습 필수...

Q1. make a string out of an array

  • join // 원하는 구분자를 넣을 수 있음. (한번 확인해보기)
{
  const fruits = ['apple', 'banana', 'orange'];
  const result = fruits.join(','); 
  console.log(result);
}

apple,banana,orange

Q2. make an array out of a string

  • split // 구분자를 꼭 넣어줘야 한다.
{
  const fruits = '🍎, 🥝, 🍌, 🍒';
  const result = fruits.split(',');
  console.log(result);
}

▶(4) ["🍎", " 🥝", " 🍌", " 🍒"]
0: "🍎"
1: " 🥝"
2: " 🍌"
3: " 🍒"
length: 4

Q3. 거꾸로 배열하기 look like this: [5, 4, 3, 2, 1]

  • reverse // 함수를 호출한 array 배열 자체도 순서가 바뀐다는 것을 유념하기.
{
  const array = [1, 2, 3, 4, 5];
  const result = array.reverse();
  console.log(result);
  console.log(array); 
}

▶(5) [5, 4, 3, 2, 1]
▶(5) [5, 4, 3, 2, 1]

Q4. make new array without the first two elements

  • slice // 원하는 부분만 리턴 - 마지막 인덱스가 배제되는 것을 주의
{
  const array = [1, 2, 3, 4, 5];
  const result = array.slice(2, 5); 
  console.log(result);
  console.log(array);
}

▶(3) [3, 4, 5]
▶(5) [1, 2, 3, 4, 5]

Class 활용

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

  • find
{
  const result = students.find((student) => student.score === 90);
  console.log(result);
}

▶Student {name: "C", age: 30, enrolled: true, score: 90}

Q6. make an array of enrolled students

  • filter
{
  const result = students.filter((student) => student.enrolled);
  console.log(result);
}

▶(3) [Student, Student, Student]

Q7. make an array containing only the students' scores - ex) [45, 80, 90, 66, 88]

  • map
{
  const result = students.map((student) => student.score);
  console.log(result);
}

▶(5) [45, 80, 90, 66, 88]

Q8. check if there is a student with the score lower than 50

  • some
  • every
{
  const result = students.some((student) => student.score < 50);
  console.log(result);

  const result2 = !students.every((student) => student.score >= 50);
  console.log(result2);
}

▶true
▶true

Q9. 평균 점수 구하기

  • reduce (가장 어려웠던 부분)
{
  const result = students.reduce((prev, curr) => prev.score + curr.score);
  console.log(result / students.length);
}

Q10. make a string containing all the scores - ex) '45, 80, 90, 66, 88'

  • 함수형 프로그래밍 예시 - map / filter / join
{
  const result = students
    .map((student) => student.score)
    .filter((score) => score >= 50)
    .join();
  console.log(result);
}

▶80,90,66,88

Q11. 오름차순 정렬하기 - ex) '45, 66, 80, 88, 90'

  • {
      const result = students
        .map((student) => student.score)
        .sort((a, b) => a - b)
        .join();
      console.log(result);
    }

    ▶45,66,80,88,90

0개의 댓글

관련 채용 정보