드림코딩_by엘리/유투브강의_JavaScript

드림코딩 by 엘리_ Array APIs & Array Function

AngeRay 2021. 9. 15. 19:06

Array APIs & Array Function


 

'use strict'

// Q1. make a string out of an array
// 구분자 전달 가능
/**
     * Adds all the elements of an array into a string, separated by the specified separator string.
     * @param separator A string used to separate one element of the array from the next in the resulting string.
        If omitted, the array elements are separated with a comma.
     */
 // join(separator?: string): string;
{
    const fruits = ['apple', 'banana', 'orange'];
    const result = fruits.join('|');
    console.log(result);
}


// Q2. make an array out of a string
// 배열로 만들기
/**
     * Split a string into substrings using the specified separator and return them as an array.
     * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
     * @param limit A value used to limit the number of elements returned in the array.
     */
// split(separator: string | RegExp, limit?: number): string[];
{
    const fruits = '🍎, 🥝, 🍌, 🍒';
    const result = fruits.split(',', 2);
    console.log(result);
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
// point!! 리턴된 배열의 값의 순서가 바꼈는데 배열 자체도 순서가 바껴있다.
// 배열 자체, 리턴된 배열도 변환
/**
     * Reverses the elements in an array in place.
     * This method mutates the array and returns a reference to the same array.
     */
// reverse(): T[];
{
    const array = [1, 2, 3, 4, 5];
    const result = array.reverse();
    console.log(result);
    console.log(array);
}

// Q4. make new array without the first two element

// splice는 삭제된 데이터가 return 즉 reslut는 삭제된 데이터가 출력
// 배열 자체에는 삭제된 데이터 제외 출력
// ** 배열 자체를 수정
{
    const array = [1, 2, 3, 4, 5];
    const result = array.splice(0, 2);
    console.log(result);
    console.log(array);
}

// 새로운 배열 창조
// result에는 새로운 배열이 할당되어 있고 array에 있는 데이터는 변화되지 않았다.
// ** 배열에서 원하는 부분만 리턴해서 받아오고 싶을때 사용
{
    const array = [1, 2, 3, 4, 5];
    const result = array.slice(2,5);
    console.log(result);
    console.log(array);
}

// 4가지 필드를 가지고 있는 Student 클래스 생성
class Student {
    constructor(name, age, enrolled, score) {
        this.name = name;
        this.age = age;
        this.enrolled = enrolled;
        this.score = score;
    }
}

const student = [
    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
/**
     * Returns the value of the first element in the array where predicate is true, and undefined
     * otherwise.
     * @param predicate find calls predicate once for each element of the array, in ascending
     * order, until it finds one where predicate returns true. If such an element is found, find
     * immediately returns that element value. Otherwise, find returns undefined.
     * @param thisArg If provided, it will be used as the this value for each invocation of
     * predicate. If it is not provided, undefined is used instead.
     */
 // find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
 // find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;

 // find의 콜백함수는 boolean을 return 한다.
 // 우리가 전달한 이 콜백함수는 배열에 있는 모든 요소들마다 하나씩 호출이 되는데
 // 즉 배열에 들어있는 아이템들마다 순차적으로 하나하나씩 호출이 되는데
 // 나중에 호출할께! 해서 콜백함수
 // find는 첫번째로 true가 나오면 해당하는 그 배열의 요소를 return해주는 API 이다.

 // arrow function - 괄호생략, return생략, ;생략
{
    const reslut = student.find((student) => student.score === 90)
    console.log(reslut);
}

// Q6. make an array of enrolled students
/**
     * Returns the elements of an array that meet the condition specified in a callback function.
     * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
     */
 // filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
 // 우리가 원하는 것만 받아올 수 있다.
{
    const reuslt = student.filter((student) => student.enrolled);
    console.log(reuslt);
}

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
/**
     * Calls a defined callback function on each element of an array, and returns an array that contains the results.
     * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
 // map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
// map은 배열안에 들어있는 요소 한가지 한가지를 다른것으로 변환해준다.
// map은 지정된 콜백함수를 호출하면서 각각의 요소들을 함수를 거쳐서 다시 새로운 값으로 변환하는것을 말한다.
// 내가 전달한 콜백함수가 어떤 일을 하냐에 따라서 다른 값으로 mapping 되어서 만들어 진다.
// map은 배열안에 들어 있는 모든 요소들을 우리가 전달해준 콜백함수를 호출하면서 콜백함수에서 가공되어진 리턴되어진 값들로 대체하는 것이다.
// 배열안에 있는 요소들을 우리가 원하는 함수를 이용해서 다른 방식의 데이터를 만들고싶을 때는 map을 이용한다.
// 콜백함수로 전달되는 전달인자는 최대한 이해하기 쉽게 작성한다.
{
    const result = student.map((student) => student.score);
    console.log(result);
}

// Q8. check if there is a student with the score lower than 50
{  
    console.clear();
    /**
     * Determines whether the specified callback function returns true for any element of an array.
     * @param predicate A function that accepts up to three arguments. The some method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value true, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
     // some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
     // 이 콜백함수는 이 배열 요소들 하나하나 마다 수행이 된다.
     // 배열에서 하나라도 조건에 만족되는 요소가 있다면 ture로 return 된다.
    const result = student.some((student) => student.score < 50);
    console.log(result);

    /**
     * Determines whether all the members of an array satisfy the specified test.
     * @param predicate A function that accepts up to three arguments. The every method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value false, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
     //every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
    // 배열에 있는 모든 요소들이 즉 배열에 들어있는 모든 요소들이 이 조건을 충족해야지만 true로 return 된다.

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

    // 배열 중에 어떤 것이라도 하나 만족되는 것이 있는지 없는지 검사할 때는 some을 이용하고
    // 모든 배열의 조건이 만족 되어야 될 때는 every를 쓰면 된다.
}

// Q9. compute students' average score
/**
     * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
 // reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
 // reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
 // previousValue는 이전에 콜백함수에서 리턴된 값들이 전달되어져 오고
 // currentValue는 배열의 아이템을 순차적으로 전달받는다.
// reduce는 배열에 있는 모든 요소의 값을 누적한다.
// curr 이라는것은 배열 하나하나씩 순차적으로 여기 curr에 전달이 되는데
// prev 라는것은 우리가 여기서 리턴한 값이 그 다음에 호출될 때 prev로 연결된다.
// 즉 우리가 리턴하는 값들이 순차적으로 prev로 전달 되는 것이다.
// 우리가 원하는 시작점 부터 모든 배열을 돌면서 어떤 값을 누적할 때 사용한다.
{
    const result = student.reduce((prev, curr) => {
        console.log('-----');
        console.log(prev);
        console.log(curr);
        return prev + curr.score;
    }, 0)
    console.log(result / student.length);
}

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
// map을 이용하게 되면 새로운 배열이 리턴된다.
// map은 배열 자체를 리턴하기 때문에 api를 섞어서 호출 가능하다.
// 이렇게 여러 apis를 묶어서 표현하는것을 함수형 프로그래밍 이라고 한다.
{
    const result = student
    .map(student => student.score)
    .filter(score => score >= 50)
    .join()
    console.log(result);
}

// Bonus!! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
/**
     * Sorts an array in place.
     * This method mutates the array and returns a reference to the same array.
     * @param compareFn Function used to determine the order of the elements. It is expected to return
     * a negative value if first argument is less than second argument, zero if they're equal and a positive
     * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
     * ```ts
     * [11,2,22,1].sort((a, b) => a - b)
     * ```
     */
 // sort(compareFn?: (a: T, b: T) => number): this;
// 콜백함수에는 a,b 이전값과 현재값이 전달되는데
{
    const result = student
    .map(student => student.score)
    .sort((a, b) => a - b)
    // .sort((a, b) => b - a)
    .join();
    console.log(result);
}