8. JS Basic (Array-Api)

Changmok LEE·2023년 2월 10일

Array-Api

1. join

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 res = fruits.join();
console.log(res); // apple,banana,orange

const res = fruits.join('|');
console.log(res); // apple|banana|orange

2. split

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 = 'apple, banana, orange';
const res = fruits.split(',');
console.log(res); // ['apple', 'banana', 'orange']

const res = fruits.split(',', 2);
console.log(res); // ['apple', 'banana']

3. reverse

make this array reverse

    /**
     * Reverses the elements in an array in place.
     * This method mutates the array and returns a reference to the same array.
     */
    reverse(): T[];
const arr = [1,2,3,4,5];
const res = arr.reverse();
console.log(res); // [5,4,3,2,1]

4. slice

make new array without the first, two elements

    /**
     * Returns a copy of a section of an array.
     * For both start and end, a negative index can be used to indicate an offset from the end of the array.
     * For example, -2 refers to the second to last element of the array.
     * @param start The beginning index of the specified portion of the array.
     * If start is undefined, then the slice begins at index 0.
     * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.
     * If end is undefined, then the slice extends to the end of the array.
     */
    slice(start?: number, end?: number): T[];
const arr = [1,2,3,4,5];
const res = arr.slice(2,5);
console.log(res); // [3,4,5]
console.log(arr); // [1,2,3,4,5]

예제(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),
];

5. find

find a student with the score 90

interface Array<T> {
    /**
     * 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;
// 콜백함수를 호출
} 
const res = students.find((student) => student.score = 90);
console.log(res); // Student { name: 'C', age: 30, enrolled: true, score: 90 }

6. filter

make an array of enrolled students

interface Array<T> {
        /**
     * 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 res = students.filter((student) => student.enrolled);
console.log(res); // [Student, Student, Student]

7. map

make an array containing only the student's scores
result should be : [45, 80, 90, 66, 88]

interface Array<T> {
/**
     * 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[];
} 
const res = students.map((student) => student.score);
console.log(res); // [45, 80, 90, 66,88]

8. some, every

check if there is a student with the score lower than 50

interface Array<T> {
    /**
     * 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;
} 
interface Array<T> {
    /**
     * 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;
} 
const res = students.some((student) => student.score < 50);
console.log(res); // true

const res1 = !students.every((student) => student.score >= 50);
console.log(res); // false

9. reduce

compute students' average score

interface Array<T> {
/**
     * 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;
} 
const res = students.reduce((prev, curr) => {
    console.log('--------');
    console.log(prev);
    console.log(curr);
    return prev+ curr.score;
}, 0); // initial value 전달(0부터 시작하도록)
console.log(res); // 369

// average
const res = students.reduce((prev, curr) => prev+ curr.score, 0); // initial value 전달(0부터 시작하도록)
console.log(res / students.length); // 73.8

// 순서 거꾸로
const res = students.reduceRight((prev, curr) => {
    console.log('--------');
    console.log(prev);
    console.log(curr);
    return prev+ curr.score;
}, 0); // initial value 전달(0부터 시작하도록)
console.log(res); // 369

10. map + join

make a string containing all the scores
result should be: '45, 80, 90, 66, 88'

const res = students.map((student) => student.score).join();
console.log(res); // 45, 80, 90, 66, 88

const res = students
.map((student) => student.score) // [45, 80, 90, 66, 88]
.filter((score) => score >= 50) // [80, 90, 66, 88]
.join(); // 80, 90, 66, 88
console.log(res); // 80, 90, 66, 88

11. sort

sort in ascending order
result should be: '45, 66, 80, 88, 90'

interface Array<T> {
    /**
     * 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 the first argument is less than the 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;
} 
// ascending order
const res = students
.map((student) => student.score)
.sort((a, b) => a - b)
.join();
console.log(res); 45, 66, 80, 88, 90

// descending order
const res = students
.map((student) => student.score)
.sort((a, b) => a - b)
.join();
console.log(res); 90, 88 ,80, 66, 45
profile
이창목

0개의 댓글