snowflakes74
snowflakes74

Reputation: 1307

filter array of ojects with max value in javascript

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

Upvotes: 0

Views: 116

Answers (2)

flyingfox
flyingfox

Reputation: 13506

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)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

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

Upvotes: 1

Related Questions