JS_배열 함수(문제 풀이)

춤추는 병따개·2023년 2월 9일
0
post-thumbnail

배열에서 유용하게 사용되는 배열 함수 몇가지만 알아보자!
출처 : 드림코딩 유튜브 채널


Q1. make a 'string' out of an array

배열을 문자열로 출력하기

{
    const fruits = ['apple', 'banana', 'orange'];
}

✅ 정답

{	//풀이1
    const fruits = ['apple', 'banana', 'orange'];
  	const result = fruits.join();
  	console.log = (result);
}
	//apple,banana,orange
{	//풀이2
    const fruits = ['apple', 'banana', 'orange'];
  	const result = fruits.join(' & ');
  	console.log = (result);
}	
	//apple & banana & orange
join(separator?: string): string;
?물음표는 옵션(사용해도 되고 안해도 된다는 표시)
* 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.

Q2. make an array out of a string

문자열을 하나의 배열로 출력하기

{
    const fruits = '🍎, 🥝, 🍌, 🍒';
}

✅ 정답

{	//풀이1
  	const result = fruits.split(',');
  	console.log(result);
}
	// (4) ['🍎', ' 🥝', ' 🍌', ' 🍒']
{	//풀이2
  	const result = fruits.split(',',2);
  	console.log(result);
}
	// (2) ['🍎', ' 🥝']
split(separator: string | RegExp, limit?: number): 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.

Q3. make this array look like this: [5, 4, 3, 2, 1]

역순으로 배열 출력하기

{
    const array = [1, 2, 3, 4, 5];
}

✅ 정답

{
    const result = array.reverse();
    console.log(result);
} 
	//(5) [5, 4, 3, 2, 1]
reverse(): T[];
T[]는 배열도 영향을 받음을 뜻함! : reverse는 출력값 뿐아니라 배열에도 영향을 줌!
* Reverses the elements in an array in place.
* This method mutates the array and returns a reference to the same array.  

Q4.사전 퀴즈//make array without the first two elements

배열의 특정 원소 없애고 출력하기

{
    const array = [1, 2, 3, 4, 5];
}

✅ 정답

{	
	const result = array.splice(0,2);
    console.log(result); //[1, 2]  result 함수로 선택된 원소
    console.log(array); //[3, 4, 5] array 반영된 결과
} 
splice(start: number, deleteCount?: number): T[];
		  //시작점			//삭제할 갯수
T[]는 배열도 영향을 받음을 뜻함! : 출력값 뿐아니라 배열에도 영향을 줌!
* 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.

Q4. make 'new' array without the first two elements'

특정 원소를 없앤 새로운 배열 출력하기

{
    const array = [1, 2, 3, 4, 5];
}

✅ 정답

{				 //0  1  2  3  4  5
  	const array = [1, 2, 3, 4, 5];
    const result = array.slice(2,5);
    console.log (result); //(3) [3, 4, 5]
    console.log (array); //(5) [1, 2, 3, 4, 5]
} 
slice(start?: number, end?: number): Int8Array;
   //시작점 여기서부터~//마지막점 ~까지! (단, 마지막 지점은 제외된다.) 
* Returns a section of an array.
* @param 'start' The beginning of the specified portion of the array.
* @param 'end' The end of the specified portion of the array. ** This is exclusive of the element at the index 'end'.

💬

'splice'는 배열에 영향을 주지만 'slice'는 기존 배열엔 영향을 주지 않는다!
A.splice() = [A배열]에서 특정 원소 삭제
A.slice() = [A배열]에서 특정 원소를 골라서 새로운 [B배열] 생성

Q5. 심화문제

예문.
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),
];

Q5-1. find a 'student' with the score 90

조건에 맞는 인자 찾기

✅ 정답

{ 
    풀이 1)
	const result = students.find(function (student) {
      return student.score === 90;
	});
	console.log(result);
  	_
	풀이 2) 에로우 함수버전
	const result = students.find((student) => student.score === 90);
	console.log(result);
	//Student {name: 'C', age: 30, enrolled: true, score: 90}
}

find(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;
* ?는 옵션, |는 or, predicate는 콜백함수 (인자는 하나만 있어도 됨!)
* Returns the value of the first element in the array where predicate is true, and undefined otherwise.
	=> predicate에 부합하는 첫번째 원소 값 하나만 찾아줌!
* @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.
	=> 트루 값 찾으면 바로 반환함! 없으면 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.

Q5-2. make an 'array' of enrolled students

조건에 맞는 인자로 이루어진 배열 만들기

✅ 정답

{ 
	const result = students.filter((student) => student.enrolled);
	console.log(result);
	//(3) [Student, Student, Student]
	//0: Student {name: 'A', age: 29, enrolled: true, score: 45}
	//1: Student {name: 'C', age: 30, enrolled: true, score: 90}
	//2: Student {name: 'E', age: 18, enrolled: true, score: 88}
}
filter(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
* ?는 옵션, |는 or, predicate는 콜백함수 (인자는 하나만 있어도 됨!)
* 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.

Q5-3. 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<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.

Q5-4. 'check' if there is a student with the score lower than 50

조건에 맞는 인자가 있는지 체크! (true값이 있는지 확인하기)

✅ 정답

{ 
	const result = students.some((student)=>student.score < 50);
    console.log(result);
	//true
}
some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
* ?는 옵션, predicate는 콜백함수 (인자는 하나만 있어도 됨!)
* Determines whether the specified callback function returns true for 'any element' of an array.
=> 조건을 충족하는 원소가 배열에 '하나라도' 있으면 콜백 함수가 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.
* @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( )

{ 
	const result = students.every((student)=>student.score < 50);
    console.log(result);
	//flase
  	// 위 문제에는 some()함수가 효율적. every()함수로 식을 짜려면 번거로워짐.
  	//const result = !students.every((student)=>student.score >= 50);
}
every(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
* ?는 옵션, predicate는 콜백함수 (인자는 하나만 있어도 됨!)
* 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.
* @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.

Q5-5. compute students' average score

평균값 구하기 (어려움 주의 ⭐️)

평균값을 구하려면 일단 누적된 수를 먼저 구해야한다!

= reduce()

❗️공부가 필요함

{  //누적 숫자 구하기 = reduce() 
	const result = students.reduce((prev, curr)=> {
		console.log('----');
		console.log(prev);  //*prev는 콜백 함수에서 리턴된 값을 전달 받음
        console.log(curr);  //*curr은 배열의 아이템을 순차적으로 전달 받음
        return prev + curr.score;  // (prev+curr).score;
    }, 0);
        console.log (result);
}

✅ 정답 평균값 구하기

{
  const result = students.reduce((prev, curr) => prev + curr.score, 0);
  consoel.log(result / students.length); 
}
//73.8
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
* ?는 옵션, predicate는 콜백함수 (인자는 최대 4개까지), =>return이 필요한 식이라는 뜻
* 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.
=> 콜백 함수는 최대 4개의 인자를 받는다.reduce메서드는 각 원소마다 콜백 함수를 호출한다.
* @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.

Q5-6. make a 'string' containing all the scores

특정 인자들만 뽑아 '문자열' 만들기

map() = 특정 인자로 배열 만들기 + join() = 배열을 문자열로 바꾸기

✅ 정답

{
  const result = students.map((student) => student.score).join('/');
  console.log(result);
}
//45/80/90/66/88

Q5-7. sorted in asceding order

오름차순으로 정렬하기

map() = 특정 인자로 배열 만들기 + sort() = 오름차순으로 정렬하기

✅ 정답

{
    const result = students
        .map((student) => student.score)
        .sort((a, b) => a-b)
        .join();
    console.log(result);
}
//45/80/90/66/88
  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 the first argument is less than the second argument, zero if they're equal, and a positive
	=> 첫 번째 인수가 두 번째 인수보다 작으면 음수 값을 반환하고 같으면 0을 반환하고 양수를 반환할 것
cheos beonjjae insuga du beonj
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. => 요소가 ASCII 문자 오름차순으로 정렬됩니다.
     [11,2,22,1].sort((a, b) => a - b) 
	*오름차순
	[11,2,22,1].sort((a, b) => b - a) 
    *내림차순
profile
FE 개발 공부 중

0개의 댓글