首页 > 解决方案 > 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')

标签: javascripttypescript

解决方案


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)


推荐阅读