[JS] Array 응용 예시

Janet·2022년 9월 1일
0

JavaScript

목록 보기
10/26
// Q1. make a string out of an array
{
  const fruits = ['apple', 'banana', 'orange'];
  // a. toString 이용
  const toString = fruits.toString();
  console.log(toString); // apple,banana,orange
  // b. join 이용
  const join = fruits.join();
  console.log(join); // apple,banana,orange
}

// Q2. make an array out of a string
{
  const fruits = '🍎, 🥝, 🍌, 🍒';
  const split = fruits.split(" ,");
  console.log(split); // ['🍎, 🥝, 🍌, 🍒']
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
  const array = [1, 2, 3, 4, 5];
  const reverseArr = array.reverse();
  console.log(reverseArr); // (5) [5, 4, 3, 2, 1]
  console.log(array); // (5) [5, 4, 3, 2, 1]
  // reverse는 배열 자체를 변화시키고 기존의 array의 return도 변경시킴
}
  
// Q4. make new array without the first two elements
{
  const array = [1, 2, 3, 4, 5];
  const slice = array.slice(2, 5);
  console.log(slice); // (3) [3, 4, 5]
  console.log(array); // (5) [1, 2, 3, 4, 5]
  // slice(첫번째 인자: 추출할 값의 index 시작지점, 두번째 인자: index의 마지막지점 + 1)
  // 마지막 지점은 배제되기때문에 끝나는 지점을 +1을 해줘야함
}

// 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 find = students.find((student) => student.score === 90);
  console.log(find); // Student {name: 'C', age: 30, enrolled: true, score: 90}
}

// Q6. make an array of enrolled students
{
  const filter = students.filter((student) => student.enrolled);
  console.log(filter);
  // (3) [Student, Student, Student]
  // enrolled(등록)한 학생 3명 출력(enrolled가 true인 대상들)
}

// Q7. make an array containing only the students scores
// result should be: [45, 80, 90, 66, 88]
{
  const map = students.map((student) => student.score);
  console.log(map); // (5) [45, 80, 90, 66, 88]
}

// Q8. check if there is a student with the score lower than 50
{
  // some: 배열의 모든 값들 중 일부라도 조건을 만족하는 값이 있는지 확인할 때
  const some = students.some((student) => student.score < 50);
  console.log(some); // true

  // every: 배열의 모든 값들이 조건을 만족하는지 확인할 때
  const every = students.every((student) => student.score < 50);
  console.log(every); // false
}

// Q9. compute students' average score
{
  const reduce = students.reduce((prev, current) => prev + current.score, 0);
  console.log(reduce / students.length); // 73.8
  // reduce: 값을 누적할때 씀. previousValue는 콜백함수에서 리턴된 값이 전달, currentValue: 배열의 item을 순차적으로 전달받음,
  // 0은 initialValue임
}

// 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); // 45,80,90,66,88
  // map으로 score를 array 형태로 받아 온 후 join을 통해 array를 string화하여 출력
}

// 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); // 45,66,80,88,90
  // map을 통해 score를 배열 형태로 받음 -> sort로 배열을 오름차순 정렬 -> join으로 배열을 string형태로 바꿈
  // sort 는 a - b 는 오름차순, b - a는 내림차순임. 그냥 sort() 라고만 선언하면 기본적으로 오름차순으로 정렬됨
}
{
 // sort 내림차순으로 정렬
  const result = students
    .map((student) => student.score)
    .sort((a, b) => b - a) // b - a 로 하면 내림차순 정렬
    .join();
  console.log(result); // 90,88,80,66,45
}
profile
😸

0개의 댓글