본문으로 바로가기

 

1. make a string out of an array (배열을 문자열로만들기)

const fruits = ['apple', 'banana', 'orange'] 
const result = fruits.join(); console.log(result); // 'apple,banana,orange'


join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

/**
* Reverses the elements in an array in place.
* This method mutates the array and returns a reference to the same array.
*/

 


1-1. make an array out of a string (문자열을 배열로 만들기)

const fruits = 'apple,banana,orange';
const result = fruits.split(','); 
console.log(result); // ["apple", "banana", "orange"]


split() 메서드는 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.
*/

 


2. make this array look like this : [1, 2, 3, 4, 5] (이 배열을 다음과 같이 만들기 : [5, 4, 3, 2, 1])

const array = [1, 2, 3, 4, 5]; 
const result = array.reverse(); 
console.log(result); // [5, 4, 3, 2, 1] 
console.log(array); // [5, 4, 3, 2, 1] 
// 위의 코드처럼 작성한다면 원본 배열까지 값이 변하는 현상이 발생한다. 
// 따라서, 아래코드와 같이 복제하여 새로운 배열을 만드는 것이 유지보수하는데 더 도움이 될 수 있다. 

const anotherArray = [1, 2, 3, 4, 5]; 
const anotherResult = Array.from(anotherArray).reverse(); 
console.log(anotherArray) // [1, 2, 3, 4, 5] 
console.log(anotherResult) // [5, 4, 3, 2, 1]


reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

/**
* Reverses the elements in an array in place.
* This method mutates the array and returns a reference to the same array.
*/

 


4. make new array without the first two elements (처음 두 요소없이 새 배열 만들기)

const array = [1, 2, 3, 4, 5]; 
const result = array.splice(2); 
console.log(result); // [3, 4, 5]


splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.

/**
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @returns An array containing the elements that were deleted.
*/

 


5. find a student with the score 90 (90점인 학생 찾기)

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) ] 
    
const result = students.find((student) => student.score === 90); 
console.log(result); // Student {name: "C", age: 30, enrolled: true, score: 90}


find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

/**
* 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.
*/

 


6. make an array of enrolled students (등록 된 학생들의 배열 만들기)

const result = students.filter((student) => student.enrolled); 
console.log(result) 
// [Student, Student, Student]0: Student {name: "A", age: 29, enrolled: true, score: 45}1: Student {name: "C", age: 30, enrolled: true, score: 90}age: 30enrolled: truename: "C"score: 90__proto__: Object2: Student {name: "E", age: 18, enrolled: true, score: 88}age: 18enrolled: truename: "E"score: 88


filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

/**
* 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.
*/

 


7. 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); // (5) [45, 80, 90, 66, 88]


map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

/**
* 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.
*/

 


8. chek if there is a student with the score lower than 50 (점수가 50 점 미만인 학생이있는 경우 확인)

// 배열에 한개라도 만족하면 
const result = students.some((student) => student.score >= 50); 
console.log(result) // true 

// 모든 배열의 조건이 만족하면 
const result2 = students.every((student) => student.score >= 50); 
console.log(result2) // false


some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.

**
* 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.
*/


every() 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다. Boolean 값을 반환합니다.

/**
* 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.
*/

 


9. compute students' average score (학생들의 평균 점수 계산)

const result = students.reduce((prev, curr) => { return prev + curr.score }, 0) // 시작값 (0부터 시작) 
console.log(result / students.length) // 73.8


reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

/**
* 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.
*/

 


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); // 45,80,90,66,88

 


11. sorted in ascending order result should be: '45, 66, 80, 88, 90' (오름차순으로 정렬하기)

const result = students.map((student) => student.score).sort((a, b) => a-b) 
// 내림차순으로 하려면 b-a .join(); console.log(result) // 45,66,80,88,90


sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

/**
* Sorts an 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)
* ```
*/