10種類の[javascript]配列関数


1. join
配列を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.
*/
join(separator?: string): string;
const fruits = ['apple', 'banana', 'orange'];
const newString1 = fruits.join();	//구분자를 넣어주지 않으면 자동으로 ,(콤마)
console.log(newString1);	//apple,banana,orange

const newString2 = fruits.join(",");
console.log(newString2);	//apple,banana,orange

const newString3 = fruits.join("|");
console.log(newString3);	//apple|banana|orange
2. 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.
*/
split(separator: string | RegExp, limit?: number): string[];
const fruits = '사과, 딸기, 바나나';
const result = fruits.split(",");
console.log(result);	// [사과, 딸기, 바나나]

const result1 = fruits.split(",", 2);
console.log(result1);	// [사과, 딸기]
3. 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 array = [1, 2, 3, 4, 5];
const reverseArr = array.reverse();
console.log(reverseArr);	// 5, 4, 3, 2, 1
console.log(array);	// 주의! 5, 4, 3, 2, 1
4. slice
配列の特定の部分(endを含まないstartからendを指定する)の関数を返します.そのまま残す
💡 spliceは円アレイ自体を修正する関数であり,sliceはアレイで受信したい部分だけを返す場合に用いる関数である.
/**
* 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[];
// Quiz: [3, 4, 5] 만 출력해보자.
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5);	//5는 포함되지 않아서 2~4
console.log(result);	// [3, 4, 5]
console.log(array);	// [1, 2, 3, 4, 5]
5~10番目の関数は、Quizが使用するデータを示します.
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
最初のパラメータコールバック関数は配列内の各要素を呼び出し、呼び出されたコールバック関数がtrueを返すと、すぐに関数を停止し、trueを返します.
/**
* 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(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;
// Quiz: 90점인 학생을 찾아보자.
const result = students.find(function(student, index) {
  	/* callback은 boolean을 리턴해야한다. 
    	* true를 리턴하게 되면 당장 find함수는 멈추게 되고 첫번째로 true가 된 student가 리턴된다.
    	*/
	return student.score === 90; // Student {name: "C", age: 30, enrolled: true, score: 90}
});

// arrow function 사용
const result1 = students.find((student) => student.score === 90);
6. 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.
*/
filter(predicate: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;
// Quiz: 수업에 등록한 학생들만 찾아서 배열로 만들어보자.
const result = students.filter((student) => student.enrolled === true);
console.log(result);	// [Student, Student, Student]
7. 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.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
// Quiz: 점수만 들어있는 새로운 배열을 만들어보자.
const result = students.map((student) => student.score);
console.log(result);	// [45, 80, 90, 66, 88]
// Quiz: 학생들 모든 점수를 string 으로 만들어보자.
const result = student.map(student => student.score).join();
console.log(result);	// 45,80,90,66,88


// Quiz: 점수가 50점 이상인 학생들의 점수를 string으로 만들어보자.
const result1 = student.map(student => student.score)
			.filter((score) => score >= 50)
			.join();

console.log(result);	// 80,90,66,88
8. sort
コピーを作成するのではなく、関数をソートします.基本ソート順は昇順です.
compareFunctionを省略すると、配列内の要素は文字列とみなされ、Unicode値の順にソートされます.
  • の戻り値が0より小さい場合、aはbより前に並べ替えられる(昇順)
  • .
  • の戻り値が0より大きい場合、降順に配列する(bはaより前)
  • .
    戻り値が0の場合、aおよびbの順序は変更されない
  • /**
    * 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)
    * ```
    */
    sort(compareFn?: (a: T, b: T) => number): this;
    // Quiz: 학생들 점수를 오름차순으로 string으로 출력해보자.
    const result = students.map(student => student.score)
      			.sort((a,b) => a-b)	// 리턴값이 0보다 작을 경우, a가 b보다 앞에 오도록 정렬
      			.join();
    
    console.log(result);	// 45,66,80,88,90
    昇順ソート
    const scores = [1, 5, 2, 3, 4];
    scores.sort((a, b) => a - b);
    console.log(scores);	//[1, 2, 3, 4, 5]
    降順ソート
    const scores = [1, 5, 2, 3, 4];
    scores.sort((a, b) => b - a);
    console.log(scores);	//[5, 4, 3, 2, 1]
    9. some
    コールバック関数は、アレイ内の各要素を実行し、アレイに条件を満たす要素がある場合はtrueを返します.
    /**
    * 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;
    // Quiz: 점수가 50점 미만인 학생이 존재하는지 확인해보자.
    const result = students.some((student) => student.score < 50);
    💡 各関数はtrueを返しますが、すべての要素が条件を満たす必要があります.
    10. 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;
    // Quiz: 학생들의 평균 점수를 구해보자.
    const result = students.reduce((prev, curr) => {
        //prev는 이전에 콜백함수에서 리턴된값이 전달되어져 오고, curr은 배열의 아이템을 순차적으로 전달받는다.
        return prev + curr.score;  //=> T 리턴해줘야한다. 리턴할때마다 prev로 전달된다.
      }, 0);  //initialValue 전달 -> prev가 0부터 시작
    
      console.log(result);  // 369
      console.log(result / students.length); // 73.8
    💡 reduceRight関数は配列の後ろから逆さまに始まる関数です.
    💕 注:DREAMコードby Elly