JavaScript 7. 배열함수

khxxjxx·2021년 5월 4일
0

드림코딩 by 엘리

목록 보기
7/11

강좌 : 유튜브 드림코딩 by 엘리

7. 배열함수

📄 Q1 ~ Q4

✍️Join

  • 배열을 문자열로 변환
  • 배열이름.join(); : 괄호안에 구분자를 넣어 설정할 수 있다
// Q1. make a string out of an array
const fruits = ['apple', 'banana', 'orange'];const result = fruits.join(', ');
  console.log(result);

✍️Split

  • 문자열을 배열로 변환
  • 배열이름.split(','); : 괄호안에 구분자를 넣지 않으면 문자열 통채로 배열에 들어간다
// Q2. make an array out of a string
const fruits = '🍎, 🥝, 🍌, 🍒';const result = fruits.split(',');
  console.log(result);
// 내가 푼 다른 방법
const result = [];
for (fruit of fruits) {
  if (fruit === ',' || fruit === ' ') {
    continue;
  }
  array.push(fruit);
}
console.log(result);

✍️Reverse

  • 배열을 내림차순으로 정렬
  • 배열이름.reverse();
// Q3. make this array look like this: [5, 4, 3, 2, 1]
const array = [1, 2, 3, 4, 5];

→ array.reverse();
  console.log(array);

✍️Slice

  • 원하는 index에서부터 새로운 배열 생성
  • const array = 배열이름.slice();
  • 괄호안에 시작할 index값을 넣어준다
// Q4. make new array without the first two elements
const array = [1, 2, 3, 4, 5];const arr = array.slice(2);
  console.log(arr);  // [3, 4, 5]
  console.log(array);  // [1, 2, 3, 4, 5]
// 내가 푼 다른 방법
const arr = array.splice(2);
console.log(arr);  // [3, 4, 5]
console.log(array);  // [1, 2]  // 원본배열의 값이 변하므로 x

📄 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),
];

✍️Find

  • 배열안의 모든 요소들이 호출되어지며 호출되어진 요소가 true이면 값을 반환하고 종료
// Q5. find a student with the score 90const result = students.find((student) => student.score === 90);
  console.log(result);

✍️Filter

  • 배열안의 모든 요소들이 호출되어지며 호출되어진 요소가 true인 값을 모아서 새로운 배열을 반환
// Q6. make an array of enrolled studentsconst result = students.filter((student) => student.enrolled);
  console.log(result);

✍️Map

  • 배열안에 들어있는 모든 요소들을 return되어진 값들로 대체되어 새로운 배열을 반환
// 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);

✍️Some

  • 배열의 요소중 하나라도 조건이 충족되면 true
// Q8. check if there is a student with the score lower than 50const result = students.some((student) => student.score < 50);
  console.log(result);  // true

✍️Every

  • 배열의 요소중 모든배열이 조건이 충족되야 true
const result2 = students.every((student) => student.score < 50);
  console.log(result2);  // false

✍️Reduce

  • reduceRight : 배열의 뒷부분부터 시작
  • prev : 이전에 콜백함수에서 return 된 값이 전달
  • curr : 배열의 아이템을 순차적으로 전달
  • '0' : 초기값
// Q9. compute students' average scoreconst result = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(result / students.length);
// 내가 푼 다른 방법
 const result = students.map((student) => student.score);
 let average = 0;
 for (let score of result) {
   average += score;
 }
 console.log(average / result.length);

📖 연습해보기

// 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);  // API를 섞어서 사용할 수 있다
// 내가 푼 다른 방법
const result = students.map((student) => student.score);
const string = result.join();
console.log(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);
profile
코린이

0개의 댓글