Home > Back-end >  Counting duplicates in object array and storing the count as a new object have error !!! react js
Counting duplicates in object array and storing the count as a new object have error !!! react js

Time:05-21

I want to counting duplicate item in my array of object,I usse this code below but I have this error : //TypeError: Cannot read properties of undefined (reading 'type')

//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: Cannot read properties of undefined (reading 'type')

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),
 
  ];
};

CodePudding user response:

As I understand it, you want to count the occurrences of unique cs values in your data array? Sure thing.

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);

outputs

[
  { cs: '10', count: 3 },
  { cs: '20', count: 1 } 
]

CodePudding user response:

First, do the counts using Array.prototype.reduce() then sort using Array.prototype.sort().

The following would also work.

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);

Swap a and b in b.count - a.count, if you want to change the order of sorting.

  • Related