86

reduceTypeScriptで配列メソッドが何をするか知っていますか?簡単な使い方の例を教えてください。

GoogleとTypeScript言語仕様を検索しましたが、適切な説明と例が見つかりませんでした。

4

6 に答える 6

124

他の答えに加えてただのメモ。

削減するために初期値が指定されている場合は、そのタイプを指定する必要がある場合があります。つまり、次のようになります。

a.reduce(fn, [])

する必要があるかもしれません

a.reduce<string[]>(fn, [])

また

a.reduce(fn, <string[]>[])
于 2017-11-24T13:54:58.193 に答える
74

reduceこれは、TypeScriptに固有のものではなく、実際にはJavaScriptの配列関数です。

ドキュメントで説明されているように: アキュムレータと配列の各値(左から右へ)に対して関数を適用して、単一の値に減らします。

配列の値を合計する例を次に示します。

let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(total);

スニペットはを生成する必要があり6ます。

于 2012-12-30T02:00:57.647 に答える
18

TypeScriptジェネリックを使用すると、次のようなことができます。

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);
于 2015-09-12T13:32:55.117 に答える
9

Reduce()は..

  • reduce()メソッドは、配列を単一の値に減らします。
  • reduce()メソッドは、配列の値ごとに(左から右に)提供された関数を実行します。
  • 関数の戻り値はアキュムレータに格納されます(結果/合計)。

そうだった ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

への変更

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

また、で使用することができます

  1. 最大を見つける
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. 繰り返されていない要素を見つけます
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6
于 2019-06-05T04:31:12.297 に答える
0

数値配列の積を計算する簡単な例。私がいつも忘れているのはvariable as type、初期アキュムレータとして渡されるパラメータの構文です。

const product = (nums: number[]): number => nums.reduce((acc: number, v: number): number => acc * v, 1 as number);
alert(product([1, 2, 3, 4]));
于 2022-01-05T12:17:26.400 に答える
0

@JohnnyHKの+1は、標準のJavascript関数であると答えます。

この関数の入力で問題が発生したため、ここに着陸しました。そのため、ここに調査結果を残しておきます。標準のIDEを使用している場合、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;


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

最初のセットは、の配列を値自体に減らすTためのTものです。

@Quentinによって言及されている2番目の使用法もあります。これは、配列をT他のタイプに減らしたい場合があるということです。ほとんどの場合、私はそれが次のように使用されているのを見ました:

const keyToValMap = [{key: 'k1', val: 1}].reduce<Record<string, number>>((map, el) => {
  map[el.key] = el.val;
  return map
}, {})
于 2022-03-03T13:55:47.757 に答える