Home > Software design >  filter array of ojects with max value in javascript
filter array of ojects with max value in javascript

Time:11-11

Hi I have an array of objects like below:

let tbrows =  [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]

I want to get the maximum value of speciecnt for each row (i.e. after filtering the array) I would like it to be

let tbrows = [{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":3}];

I am using the following code that I found on the web to filter an array but it only filters on one attribute of object.

const max2 = tbrows.reduce((op, item) => op = op > item.speciescnt? op : item.speciescnt, 0);

CodePudding user response:

You can also using reduce() to do it

let tbrows =  [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]

let result = tbrows.reduce((a,c) => {
  let obj = a.find(i => i.rowindx == c.rowindx)
  if(!obj){
    a.push(c)
  }else if(c.speciescnt > obj.speciescnt){
   obj.speciescnt = c.speciescnt
  }
  return a
},[])

console.log(result)

CodePudding user response:

Turn the array into an object (right now, you're trying to turn it into just a number). Have the object be indexed by the row index, with the associated value for that row as the highest speciecnt found so far. Then you can turn the object back into an array.

const input = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}];

const grouped = {};
for (const { rowindx, speciescnt } of input) {
  grouped[rowindx] = Math.max(grouped[rowindx] ?? -Infinity, speciescnt);
}
const output = Object.entries(grouped)
  .map(([rowindx, speciescnt]) => ({ rowindx, speciescnt }));
console.log(output);

  • Related