Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript objects array filter by minimum value of an attribute

I need to filter this object array by minimum value of 'rest' attribute. This is an one way to do it. Is there any other ways ?

'data' variable is a result of chained function. Is there any other way to do this without calling 'data' variable again inside Math.min() function.

let data = 
[ { size: 5, qty: 2, rest: 0 },
  { size: 2, qty: 5, rest: 0 },
  { size: 1, qty: 10, rest: 0 },
  { size: 3, qty: 3, rest: 1 },
  { size: 4, qty: 2, rest: 2 } ]

let result = data.filter(e=> e.rest === Math.min(...data.map(f=>f.rest) ) );
console.log(result);

// result is
//[ { size: 5, qty: 2, rest: 0 },
//  { size: 2, qty: 5, rest: 0 },
//  { size: 1, qty: 10, rest: 0 }]
like image 613
Crizy Sash Avatar asked Nov 01 '18 08:11

Crizy Sash


1 Answers

The easiest way is to pull the min function out of the filter like this:

let min = Math.min(...data.map(item => item.rest))

This is much more efficient as we are no longer loop over the data to find the min for every iteration of the filter.

We now have n * 2 passes instead of n^2 passes. (n is the size of your data set, 5 in this case)

Full example below:

   let data = [ 
     { size: 5, qty: 2, rest: 0 },
     { size: 2, qty: 5, rest: 0 },
     { size: 1, qty: 10, rest: 0 },
     { size: 3, qty: 3, rest: 1 },
     { size: 4, qty: 2, rest: 2 } 
   ]

  let min = Math.min(...data.map(item => item.rest))
  let result = data.filter(item => item.rest === min)
  console.log(result)

Hope this helps!

Lloyd

like image 190
Lloyd Avatar answered Oct 19 '22 23:10

Lloyd