동캄의 코딩도장

JS [array API] 본문

front/HTML&CSS&JS

JS [array API]

동 캄 2022. 1. 24. 14:13
// 01. make a string out of an array O
{
    const fruits= ['apple','banana','orange'];
    //console.log(fruits.toString());
    const result = fruits.join();
    console.log(result);
}

// 02. make an array out of a string  X
{
    const fruits='apple,cherry,banana,coconut';
    const result = fruits.split(',');
    console.log(result)
}

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

// 04. make this array without the first tow elements O
{  
    const array=[1,2,3,4,5];
    // result=array.filter((item)=>item>2);
    // console.log(result);
    // splice는 배열 자체 수정
    // slice는 새로운 배열을 생성
    const result = array.slice(2,5);
    console.log(result);
}

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

// 05. find a studnet with the score 90 X
{
    // const result = students.find(function(student,index){
    //     return student.score===90;
    // });
    const result = students.find((student)=> student.score===90);
    console.log(result);
}

// 06 make an array of enrolled students
{
    const result = students.filter((student)=>student.enrolled===true);
    console.log(result);
}

// 07. make an array containing only the student;s scores result should be: [45,80,90,66,88] X
{
// 배열의 각 요소를 하나씩 꺼내 mapping
    const result =students.map((student)=>student.score)
    console.log(result);
}

// 08. check if there is a student with the score lower than 50 O
{
    const result = students.some((student)=> student.score<50);
    console.log(result);

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

// 09. compute student's average score X
{
    // 배열을 순차적으로 돌면서 값을 누적하는 API
    const result = students.reduce((prev,curr)=>prev+curr.score,0);
    console.log(result /students.length);
    //reduce right은 배열의 반대쪽(오른쪽)부터 시작
}

// 10. 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);
}

// 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);
}

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [call back]  (0) 2022.01.25
JS [JSON]  (0) 2022.01.25
JS [array]  (0) 2022.01.24
JS [Object]  (0) 2022.01.24
JS [Class]  (0) 2022.01.24