javascript - Javascript:对数组中每种类型的计数和排序数
问题描述
我有一个这样的数据集
const data = [
{category: 'fish'; age: '10'; color: 'red'; },
{category: 'fish'; age: '9'; color: 'red'; },
{category: 'fish'; age: '8'; color: 'blue'; },
{category: 'fish'; age: '7'; color: 'blue'; },
{category: 'birds'; age: '10'; color: 'red'; },
{category: 'birds'; age: '9'; color: 'red'; },
{category: 'birds'; age: '8'; color: 'blue'; },
{category: 'birds'; age: '7'; color: 'blue'; },
]
但我需要能够在一个类似的函数中对它们进行计数和排序。
const count = (data: any) => {
// How to count how many of each category without hard coding fish or birds
return [
{category: 'fish'; total: 4},
{category: 'birds'; total: 4},
]
}
const summary = count(data);
并对它们进行排序...
const sort = (data: any, onlyShow: string, sortBy: string | number, ascDesc: number) => {
// How to only show the birds and then sort by age in ascending order
return [
{category: 'birds'; age: '7'; color: 'red'; },
{category: 'birds'; age: '8'; color: 'red'; },
{category: 'birds'; age: '9'; color: 'blue'; },
{category: 'birds'; age: '10'; color: 'blue'; },
]
}
const sortedData = sort(data, 'birds', 'age', '-1')
解决方案
const data = [
{category: 'fish', age: '10', color: 'red' },
{category: 'fish', age: '9', color: 'red' },
{category: 'fish', age: '8', color: 'blue'},
{category: 'fish', age: '7', color: 'blue' },
{category: 'birds', age: '10', color: 'red' },
{category: 'birds', age: '9', color: 'red' },
{category: 'birds', age: '8', color: 'blue' },
{category: 'birds', age: '7', color: 'blue' },
];
const count = (data) => {
// How to count how many of each category without hard coding fish or birds
return data.reduce((t, v) => {
let f = t.find(i => i.category == v.category);
if(f){
f.total++;
}else{
t.push({"category": v.category, "total": 1});
}
return t;
}, []);
}
const summary = count(data);
console.log(summary);
const sort = (data, onlyShow, sortBy, ascDesc) => {
// How to only show the birds and then sort by age in ascending order
return data
.filter(v => v.category == onlyShow)
.sort((a, b) => (+ascDesc) ? a[sortBy] - b[sortBy] : b[sortBy] - a[sortBy])
}
const sortedData = sort(data, 'birds', 'age', '-1');
console.log(sortedData)
推荐阅读
- php - 如何在每个 api 调用上验证 psr-jwt 令牌
- node.js - 有没有办法使用节点 js Multer 上传文件夹?
- python - 在另一个成对的 bin 数组中获取数据数组最小值的最快方法
- javascript - 你能控制基于状态变化的功能性反应组件的重新渲染吗?
- c# - 有没有办法将列表从 android 项目传递到 xamarin.forms 项目中的 MainPage
- c# - C#中数组类型数据结构的选择排序时间复杂度
- html - 我如何在 css 中使用 nav 和 main-nav
- python - 如果对熊猫数据框python进行其他操作
- node.js - 如何创建 .deb 包以便更新时不会覆盖特定文件?
- c - 为什么第二个差异与其他差异如此不同,在循环中使用 gettimeofday?