JS-8일차(array API)

김혜성·2021년 7월 9일
0

프론트엔드

목록 보기
11/17

join

array -> string

  • fruits.join('|');
  • 구분자가 | 이다 (default는 쉼표)

split

string -> array

  • fruits.split(',')

reverse

array.reverse(): 거꾸로

splice

array.splice(num1, num2) : 인덱스번호 num1부터 num2개만큼 컽

slice

array.slice(num1, num2): num1~num2-1까지 컽

find

body가 true면 return
students.find((student) => student.score === 90);

filter

body가 true인 요소 다 return
students.filter((student) => student.enrolled)

map

각 요소의 obj 등 매칭되는거 return
students.map((student) => student.score);

some

하나만 true여도 true
students.some((student) => student.score < 50)

every

모두가 true여야 true
students.every((student) => student.score >= 50);

reduce

codes


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

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

// Q3. make this array look like this: [5, 4, 3, 2, 1] - reverse
// reverse는 return값도 뒤집은 배열이지만 원본배열도 뒤집히게 됨!
{
    const array = [1, 2, 3, 4, 5];
    console.log(array.reverse());
    console.log(array);
}

// Q4. make new array without the first two elements - slice
// splice는 기존배열에서 제거되는 애들을 return함
// slice를 해야 제거하고 남은 애들을 return함
{
    const array = [1, 2, 3, 4, 5];
    console.log(array.slice(2,array.length));
    const result = array.splice(0,2);
    console.log(array);
}

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((val) => val.score===90);
    console.log(result);
    // stupid way
    students.forEach((value) =>{
        if (value.score === 90){
            console.log(value.name);
        }
    });
}

// Q6. make an array of enrolled students - filter
{
    const result = students.filter((val) => val.enrolled);
    console.log(result);
    // stupid way
    enrolled_stu = [];
    students.forEach((value) =>{
        if (value.enrolled){
            enrolled_stu.push(value.name);
        }
    });
    console.log(enrolled_stu);
}

// Q7. make an array containing only the students' scores - map
// result should be: [45, 80, 90, 66, 88]
{
    const result = students.map((val) => val.score);
    console.log(result);
    // stupid way
    stu_scores = [];
    students.forEach((value) => {
        stu_scores.push(value.score);
    });
    console.log(stu_scores);
}

// Q8. check if there is a student with the score lower than 50 - some
// some: 하나라도 조건만족이 있으면 true, 다 없으면 false
// every: 모두 조건만족이면 true, 하나라도 없으면 false
{
    const result = students.some((val) => val.score < 50);
    console.log(result);
    // stupid way
    students.forEach((value) => {
        if (value.score < 50){
            console.log(`${value.name} student's score is lower than 50`);
        }
    });
}

// Q9. compute students' average score - reduce
// reduce: accumulated result - 누적시키는 애다
// reductRight: 배열의 뒤에서부터 시작하는 reduce
{
    const result = students.reduce((prev, curr) =>prev + curr.score, 0);
    console.log(result / students.length);

    // stupid way
    let tot = 0;
    for (value of students){
        tot += value.score;
    }
    let avg = tot / students.length;
    console.log(`average score: ${avg}`);
}

// Q10. make a string containing all the scores - mixed(map & join)
// result should be: '45, 80, 90, 66, 88'
{
    const result = students
        .map((val) => val.score)
        .filter(score => score>50)
        .join();
    console.log(result);

    stu_scores = [];
    students.forEach((value) => {
        stu_scores.push(value.score);
    });
    console.log(stu_scores.toString());
}

// 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개의 댓글