const distinctArray = array => {
const cleanList = array.filter((value1, index, array) => {
// findIndex : 同じ要素があればそのインデックスを返す
// nameの値が同じもののインデックスと全体のインデックスが同じものだけ抽出
return array.findIndex(value2 => value1.name === value2.name) === index;
});
return cleanList;
};
const users = [
{ name: 'tkd1', age: 18 },
{ name: 'tkd2', age: 20 },
{ name: 'tkd3', age: 22 },
{ name: 'tkd2', age: 25 },
{ name: 'tkd3', age: 26 }
];
const distinctUsers = distinctArray(users);
console.log(distinctUsers); // [ { name: 'tkd1', age: 18 },{ name: 'tkd2', age: 20 },{ name: 'tkd3', age: 22 },]
const sortByTime = (array: any) => {
return array.sort((a: any, b: any) => {
if (a.time < b.time) return -1
if (a.time > b.time) return 1
return 0
})
}
const fruits = [ { orange: 100, apple: 120 }, { orange: 120, apple: 180 }, { orange: 130, apple: 240 }, { orange: 140, apple: 120 }, { orange: 150, apple: 180 } ];
const total = fruits.reduce((acc, currentValue) => {
return acc + currentValue.orange;
}, 0);
console.log(total);
const users = [
{ name: 'tkd1', age: 18 },
{ name: 'tkd2', age: 20 },
{ name: 'tkd3', age: 22 },
{ name: 'tkd2', age: 25 },
{ name: 'tkd3', age: 26 }
];
// 最大
const maxAgeUser = users.reduce((acc, currentValue, index) =>
acc.age > currentValue.age ? acc : currentValue
);
console.log(maxAgeUser);
// 最小値
const minAgeUser = users.reduce((acc, currentValue, index) =>
acc.age < currentValue.age ? acc : currentValue
);
console.log(minAgeUser);