Harts
Harts

Reputation: 4103

Filter an array of object to get the largest remaining capacity

Given I have an array of object such as

let discList = [{
"id" : 1,
"capacity" : 100,
"used" : 50
}, {
"id" : 2,
"capacity" : 200,
"used" : 10
}, {
"id" : 3,
"capacity" : 50,
"used" : 10}]

Is there a way to filter this array such that I get the item for the largest remaining capacity?

remainingCapacity = capacity - used;

In the above example, I'm hoping to get the 2nd item. Since

1st item = 100-50 = 50
2nd item = 200-10 = 190
3rd item = 50-10 = 40

Upvotes: 0

Views: 69

Answers (3)

D. Seah
D. Seah

Reputation: 4592

should be easy with reduce

const discList = [{
  "id": 1,
  "capacity": 100,
  "used": 50
}, {
  "id": 2,
  "capacity": 200,
  "used": 10
}, {
  "id": 3,
  "capacity": 50,
  "used": 10
}];

console.log(discList.reduce((max, {capacity, used}) => {
  return Math.max(max, capacity - used);
}, 0));

Upvotes: 1

ggorlen
ggorlen

Reputation: 57446

You can use array.reduce:

let discList = [{
  "id" : 1,
  "capacity" : 100,
  "used" : 50
}, {
  "id" : 2,
  "capacity" : 200,
  "used" : 10
}, {
  "id" : 3,
  "capacity" : 50,
  "used" : 10}
];

const mostRemainingCapacity = discList.reduce((a, e) => 
  e.capacity - e.used > a.capacity - a.used ? e : a, 
  {capacity: -Infinity, used: Infinity}
);

console.log(mostRemainingCapacity);

Explanation

Begin reduction with an object that has the worst possible remaining capacity, namely, negative infinity capacity and infinity space used. Iterating over each element, compare its remaining capacity to the best so far and return the better of the two.

Upvotes: 1

Blue
Blue

Reputation: 22921

reduce() is the easiest way to go. Gradually loop through the array, and keep replacing the object with the highest object. By the end of the array, you'll have the max:

let discList = [{
  "id" : 1,
  "capacity" : 100,
  "used" : 50
  }, {
  "id" : 2,
  "capacity" : 200,
  "used" : 10
  }, {
  "id" : 3,
  "capacity" : 50,
  "used" : 10
}]

var max = discList.reduce(function(prev, current) {
    return (prev.capacity - prev.used > current.capacity - current.used) ? prev : current
});

console.log(max);

I'd avoid going the sorting route, as it causes a lot of unnecessary comparisons, and will get more costly the greater the size of the array (Due to the steps required to reorder all the elements)

Upvotes: 2

Related Questions