Array APIs - find(), findIndex(), filter(), map(), some(), every(), reduce(), sort()

2022. 10. 7. 16:29Javascript

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형

find : 배열을 순회하며 요소들 중, 조건에 만족하는 첫 번째 요소만 반환

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;
/**
 * 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.find((score) => {
	return score > 50;
})
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //75, 배열이 아니라, 요소를 반환

 

findIndex : 배열을 순회하며 요소들 중, 조건에 만족하는 첫 번째 요소의 인덱스만 반환

findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
/**
 * Returns the index of the first element in the array where predicate is true, and -1
 * 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,
 * findIndex immediately returns that element index. Otherwise, findIndex returns -1.
 * @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 scores = [48, 75, 78, 96, 88];
const result = scores.findIndex((score) => {
	return score > 50;
});
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //1, 조건을 가장 먼저 만족하는 인덱스 값만 반환

 

filter : 배열을 순회하며 요소들 중,  조건에 만족하는 요소들을 모아서 새로운 배열로 반환

filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
/**
 * 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(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.filter((score) => {
	return score > 50;
});
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //[75, 78, 96, 88], 조건에 만족하는 요소들을 새로운 배열로 반환

 

map : 배열을 순회하며 요소 각각의 값을  다른 값으로 맵핑하여 새로운 배열로 반환

map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
/**
 * 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.map((score) => {
	return score * 2;
});
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //[96, 150, 156, 192, 176], 배열을 순회하며 요소 각각의 값을 다른 값으로 맵핑하여 새로운 배열로 반환

 

some : 배열을 순회하며 요소들 중, 하나의 요소만 만족해도 true 반환

some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
/**
 * 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.some((score) => {
	return score > 85;
});
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //true, 하나의 요소만 만족해도 true 반환

 

every : 배열을 순회하며 요소들 중, 모든 요소가 조건에 만족해야 true 반환

every<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): this is S[];
/**
 * 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;
/**
 * 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.every((score) => {
	return score > 85;
});
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //false, 모든 요소가 조건에 만족해야 true 반환

 

reduce : 배열을 순회하며 함수의 실행 값을 누적하여 하나의 결과 값을 반환

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;
/**
 * 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<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
/**
 * 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.
 */
const scores = [48, 75, 78, 96, 88];
const result = scores.reduce((prev, curr) => { //이전값, 현재값
	return prev + curr; //반환되는 값은 다음 콜백함수의 이전 값으로 전달됨
}, 0);//초기값 0으로 세팅
console.log(scores); //[48, 75, 78, 96, 88]
console.log(result); //385, 콜백함수에서 실행된 누적된 결과값으로 리턴함

배열 요소들의 평균값 구하기

const scores = [48, 75, 78, 96, 88];
const result = scores.reduce((prev, curr) => { 
	return prev + curr / scores.length;
}, 0);
console.log(result); //77, 요소들의 평균값 계산

 

sort : 배열의 요소를 적절한 위치에 정렬한 후, 그 배열을 반환

sort(compareFn?: (a: T, b: T) => number): this;
/**
 * 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)
 * ```
 */

오름차순

const scores = [48, 75, 78, 96, 88];
const result = scores.sort((a, b) => { 
	return a - b; //오름차순
});
console.log(scores); //[48, 75, 78, 88, 96], 기존의 배열을 업데이트
console.log(result); //[48, 75, 78, 88, 96]

내림차순

const scores = [48, 75, 78, 96, 88];
const result = scores.sort((a, b) => { 
	return b - a; //내림차순
});
console.log(scores); //[96, 88, 78, 75, 48], 기존의 배열을 업데이트
console.log(result); //[96, 88, 78, 75, 48]
반응형