본문 바로가기

프로그래밍/JavaScript

Javascript ES6 Array APIs 정리

// Q1. make a string out of an array
{
  const fruits = ['apple', 'banana', 'orange'];
  
  fruits.join();	// result : apple,banana,orange
  fruits.join('|');	// result : apple|banana|orange
}

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

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
  const array = [1, 2, 3, 4, 5];
  
  array.reverse();
}

// Q4. make new array without the first two elements
{
  const array = [1, 2, 3, 4, 5];
  
  // splice : array에서 0번째부터 2개의 값을 삭제. array = [3,4,5]
  array.splice(0,2);
  
  // slice : array값은 유지, 2번째부터 4번째까지(5번째는 제외) 원하는것만 리턴. 
  // array = [1,2,3,4,5], result = [3,4,5] 
  array.slice(2,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
{
  students.find((student) => student.score === 90);
}

// Q6. make an array of enrolled students
{
  students.filter((student) => student.enrolled);
}

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

// Q8. check if there is a student with the score lower than 50
{
  students.some((student) => student.score < 50);	// 하나라도 조건에 해당되면 true 반환
  students.every((student) => student.score < 50);	// 전체가 조건에 해당되면 true 반환
}

// Q9. compute students' average score
{
  let sum = students.reduce((prev,curr) => prev + curr.score, 0);
  let average = sum/students.length;
}
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
   students.map((student) => student.score).join();
}

// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
   students.map((student) => student.score).sort((a, b) => a - b).join();
}

 

 

출처 : https://www.youtube.com/watch?v=3CUjtKJ7PJg&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=9 

 

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

JavaScript 유용한 문법  (0) 2023.05.24