Last active
February 11, 2022 04:36
-
-
Save lightsound/a929d5f5e2f289f2686b73856ac8aaf1 to your computer and use it in GitHub Desktop.
Reduce関数ライブ講座で使用したコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 一番シンプルな例 | |
| const input = [1, 2, 3, 4]; | |
| const output = input.reduce((prev, current) => { | |
| return prev + current; | |
| }); | |
| console.log(output); // 10 |
Author
Author
オブジェクト配列内のプロパティを足す例
const input = [
{ name: "foo1", age: 10 },
{ name: "foo2", age: 20 },
{ name: "foo3", age: 30 },
{ name: "foo4", age: 40 },
];
const output = input.reduce((prev, current) => {
return prev + current.age;
}, 0);
console.log(output); // output: 100
Author
オブジェクト配列内のプロパティでgroupByする例
const input = [
{ name: "foo1", lang: "ja" },
{ name: "foo2", lang: "en" },
{ name: "foo3", lang: "ja" },
{ name: "foo4", lang: "en" },
];
const output = input.reduce((prev, current) => {
return {
...prev,
[current.lang]: prev[current.lang] ? [...prev[current.lang], current.name] : [current.name],
};
}, {});
console.log(output);
// {
// ja: ["foo1", "foo3"],
// en: ["foo2", "foo4"],
// }
Author
オブジェクト配列内のプロパティでgroupByする例(TypeScript)
const input = [
{ name: "foo1", lang: "ja" },
{ name: "foo2", lang: "en" },
{ name: "foo3", lang: "ja" },
{ name: "foo4", lang: "en" },
] as const;
type Lang = typeof input[number]["lang"];
const output = input.reduce((prev, current) => {
return {
...prev,
[current.lang]: prev[current.lang] ? [...prev[current.lang], current.name] : [current.name],
};
}, {} as { [key in Lang]: string[] });
console.log(output);
// {
// ja: ["foo1", "foo3"],
// en: ["foo2", "foo4"],
// }
Author
オブジェクト配列内のプロパティでgroupByする例(TypeScript + 関数の引数で分割代入)
const input = [
{ name: "foo1", lang: "ja" },
{ name: "foo2", lang: "en" },
{ name: "foo3", lang: "ja" },
{ name: "foo4", lang: "en" },
] as const;
type Lang = typeof input[number]["lang"];
const output = input.reduce((prev, { lang, name }) => {
const prevArray = prev[lang];
return {
...prev,
[lang]: prevArray ? [...prevArray, name] : [name],
};
}, {} as { [key in Lang]: string[] });
console.log(output);
// {
// ja: ["foo1", "foo3"],
// en: ["foo2", "foo4"],
// }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
初期値がある例(ループ回数が一度多くなります)