Open5
JavaScript 逆引き事典
本スクラップでは、現場でよく使う JavaScript のテクニックを利用シーンをもとに綴ります。
オブジェクトを含む配列をプロパティでグループ化
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
const groupBy = (objectArray: any[], property: string) => {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) acc[key] = [];
acc[key].push(obj);
return acc;
}, {});
};
const groupedPeople = groupBy(people, 'age');
/**** 結果 ****
{
"20": [{ "name": "Max", "age": 20 }, { "name": "Jane", "age": 20 }],
"21": [{ "name": "Alice", "age": 21 }],
}
****/
オブジェクトを含む配列をソートする
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 },
{ name: 'Tom', age: 23 },
];
const sortBy = <T extends Record<string, any>>(
target: T[],
key: string,
type: 'ascending' | 'descending' = 'descending',
) => {
switch (type) {
case 'ascending':
return target.sort((a, b) => a[key] - b[key]);
case 'descending':
return target.sort((a, b) => b[key] - a[key]);
default: {
const strangeValue: never = type;
throw new Error(`${strangeValue} is not Type.`);
}
}
};
const sortedPeople = sortBy(people, 'age');
/**** 結果 ****
[
{ "name": "Tom", "age": 23 },
{ "name": "Alice", "age": 21 },
{ "name": "Max", "age": 20 },
{ "name": "Jane", "age": 20 },
]
****/
オブジェクトの配列の値の合計値を出す
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Tom', age: 23 },
];
const sum = (objectArray: any[], property: string) => {
return objectArray.reduce((previousValue, currentValue) => previousValue + currentValue[property], 0);
};
console.log(sum(people, 'age')) // logs 64
オブジェクトの比較
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Tom', age: 23 },
];
const person = { name: 'Mix', age: 20 };
const has = people.some(
(v) => JSON.stringify(v) === JSON.stringify(person),
); // -> true