[JS] Array 메서드 정리

An overview of array methods
Apr 14, 2023
[JS] Array 메서드 정리
목차
 

join

join(separator?: string): string;
Definition
Adds all the elements of an array into a string, separated by the specified separator string. ⇒ separator를 이용하여 배열의 모든 요소를 더하여 문자열로 바꿔준다.
@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.
⇒ seperator string은 다 더해진 문자열에서 각 요소를 하나씩 분리 시킨다. seperator가 없자면, 요소들은 콤마를 기본값으로 분리된다.
// Q1. make a string out of an array { const fruits = ['apple', 'banana', 'orange']; const fruits_join = fruits.join(); } // 출력 결과 apple, banana, orange

split

split(separator: string | RegExp, limit?: number): string[];
Definition
Split a string into substrings using the specified separator and return them as an array. ⇒ seperator를 이용하여 문자열을 여러 다른 하위문자열로 분리하고, 이를 배열로 반환한다.
@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. ⇒ seperator는 문자열을 분리한다. seperator가 없다면, 문자열 전체를 한 뭉탱이로 넣은 배열을 반환한다. (요소 1개)
@param limit
A value used to limit the number of elements returned in the array. ⇒ 반환하는 요소의 갯수를 조절할 수 있다.
{ const fruits = 'apple, banana, orange'; const result = fruits.split(); console.log(result); } // 출력 결과 [ 'apple, banana, orange' ]

reverse

reverse(): T[];
Definition
Reverses the elements in an array in place. ⇒ 배열안의 요소값을 뒤집는다.
This method mutates the array and returns a reference to the same array. ⇒ 이 메서드는 배열 자체도 뒤집고, 그 배열 자체를 반환한다.
mutable?
yes, it’s mutable
{ const array = [1, 2, 3, 4, 5]; console.log(array.reverse()); } // 출력 결과 [ 5, 4, 3, 2, 1 ]

splice

splice(start: number, deleteCount?: number): T[]; * 실제 배열도 수정한다
Definition
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. ⇒ zero-based로 제거 시작 포인트이다.
@param deleteCount
The number of elements to remove. ⇒ 제거할 요소의 갯수
@returns
An array containing the elements that were deleted. ⇒ 제거한 요소를 반환
mutable?
yes, it’s mutable

slice

slice(start?: number, end?: number): T[];
Definition
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. ⇒ 예를 들어, -2는 배열에서 뒤에서 2번째 요소를 말한다.
@param start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0. ⇒ 배열에서의 특정 포션의 시작점. 만약 start가 정의되지 않았다면, 슬라이스는 인덱스 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. ⇒ 배열에서의 특정 포션의 끝. end부분은 요소에서 제외된다. 만약 end가 정의되지 않았다면, 슬라이스는 배열의 마지막으로 연장된다.
mutable?
no, it’s immutable
{ const array = [1, 2, 3, 4, 5]; console.log(array.slice(2)); } // 출력 결과 [3, 4, 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), ];

find

find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;

predicate

find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
Definition
Returns the value of the first element in the array where predicate is true, and undefined otherwise. ⇒ predicate가 true 를 만족하는 첫 요소를 반환하고, 없다면 undefined를 반환한다.
@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. ⇒ find 함수는 predicate를 딱 한번 불러 true를 불러올 값을 찾을 때까지 배열의 각 요소를 오름차순으로 확인한다. 그 요소를 발견하면, 그 즉시 그 요소를 반환하고, 없다면 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.
{ const result = students.find((student) => student.score === 90); console.log(result); } // 출력 결과 Student { name: 'C', age: 30, enrolled: true, score: 90 }

filter

filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
Definition
Returns the elements of an array that meet the condition specified in a callback function. ⇒ callback 함수 (predicate)의 조건에 부합하는 모든 요소를 배열에서 반환한다. (다른 것들이 달라도 조건에만 부합하는 모든 요소를 반환)
@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. ⇒ predicate 함수는 3개 정도의 arguments를 가진다. filter 메서드는 predicate 함수를 배열의 모든 요소를 돌 때 마다 부른다.
@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.
{ const result = students.filter((student) => student.enrolled === true); console.log(result); } // 출력 결과 [ Student { name: 'A', age: 29, enrolled: true, score: 45 }, Student { name: 'C', age: 30, enrolled: true, score: 90 }, Student { name: 'E', age: 18, enrolled: true, score: 88 } ]

map

map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
Definition
Calls a defined callback function on each element of an array, and returns an array that contains the results. ⇒ 정의된 callback 함수를 불러 배열의 각 요소를 돌고, 그 결과값을 포함한 배열을 반환한다.
@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. ⇒ 3개의 인자를 가진다. filter 메서드는 callback 함수를 배열의 모든 요소를 돌 때 마다 부른다.
@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.
{ const result = students.map((student) => student.score); console.log(result); } // 출력 결과 [ 45, 80, 90, 66, 88 ]

some

some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
Definition
Determines whether the specified callback function returns true for any element of an array. ⇒ 배열의 요소에서 하나라도 callback 함수 조건에 맞는 요소가 있으면 true를 반환한다.
@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. 3개의 인자를 가진다. some 메서드는 배열에서 true 값을 만족하는 요소가 있을때까지 각 요소를 돌때마다 predicate를 부르거나 배열 끝까지 돈다.
@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.
{ const result = students.some((student) => student.score < 50); console.log(result); } // 출력 결과 true

every

every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
Definition
Determines whether all the members of an array satisfy the specified test. ⇒ 배열의 모든 요소가 조건에 충족해야 true를 반환한다.
@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. ⇒ 3개의 인자를 가진다. every 메서드는 배열에서 true 값을 만족하는 요소가 있을때까지 각 요소를 돌때마다 predicate를 부르거나 배열 끝까지 돈다.
@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.
* * @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. */

reduce

* 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;

findIndex

findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;
Method of Array instances returns the index of the first element in an array that satisfies the provided testing function.

Syntax

findIndex(callbackFn) findIndex(callbackFn, thisArg)

Return Value

The index of the first element in the array that passes the test. Otherwise, -1.
콜백 함수를 통한 테스트를 통과한 요소들의 인덱스를 반환
 
 
 
Share article
RSSPowered by inblog