开发者问题收集

计算对象数组中的重复项并将计数存储为新对象时出现错误 !!! react js

2022-05-21
946

我想计算对象数组中的重复项,我使用下面的代码,但出现此错误: //TypeError:无法读取未定义的属性(读取“类型”)

//this is my array 
data[
1:{cs:'10', name:'a' , age},
2:{cs:'20', name :'b', age:'25'},
3:{cs:'10', name :'h', age:'51'},
4:{cs:'10', name :'g', age:'30'},

...]
//this is my result that i want
finalArray[
{cs:'10', count :3},
{cs:'20', count :1 },
...]

TypeError:无法读取未定义的属性(读取“类型”)

const prepareSeries = (data, sectors) => {

  let finalArray = [{}];
  const map = new Map();

  finalArray.forEach(function (stockItem) {
    if (map.has(stockItem.cs)) {
      map.get(stockItem.cs).count++;
    } else {
      map.set(stockItem.cs, Object.assign(stockItem, { count: 1 }));
    }
  });
  finalArray = [...map.values()];
  const result = Object.entries(finalArray)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10);
  return [
    console.log(result),
 
  ];
};
2个回答

据我了解,您想要计算 data 数组中唯一 cs 值的出现次数吗?当然可以。

const data = [
  { cs: "10", name: "a", age: "72" },
  { cs: "20", name: "b", age: "25" },
  { cs: "10", name: "h", age: "51" },
  { cs: "10", name: "g", age: "30" },
];

const countsByCs = {};
data.forEach(({ cs }) => {
  countsByCs[cs] = (countsByCs[cs] || 0) + 1;
});
const finalArray = Object.entries(countsByCs)
  .map(([cs, count]) => ({ cs, count }))
  .sort((a, b) => b.count - a.count);

console.log(finalArray);

输出

[
  { cs: '10', count: 3 },
  { cs: '20', count: 1 } 
]
AKX
2022-05-21

首先,使用 Array.prototype.reduce() 进行计数,然后使用 Array.prototype.sort() 进行排序。

以下方法也有效。

const data = [
  { cs: "10", name: "a", age: "31" },
  { cs: "20", name: "b", age: "25" },
  { cs: "10", name: "h", age: "51" },
  { cs: "10", name: "g", age: "30" },
];

const output = Object.entries(
  data.reduce((prev, { cs }) => {
    prev[cs] = prev[cs] ? prev[cs] + 1 : 1;
    return prev;
  }, {})
)
  .map(([cs, count]) => ({ cs, count }))
  .sort((a, b) => b.count - a.count);

console.log(output);

如果要更改排序顺序,请在 b.count - a.count 中交换 ab

Amila Senadheera
2022-05-21