1

I have an array of objects like below. How to return an array of objects containing the minimum value of bidAmount?

[
{userId:2,bidAmount:9200},
{userId:3,bidAmount:8500},
{userId:4,bidAmount:8100},
{userId:5,bidAmount:8100}
]

Expected result:

[
{userId:4,bidAmount:8100},
{userId:5,bidAmount:8100}
]

I tried Array.reduce to find minimum but it returns only one object

var min = result.reduce(function(res, obj) {
    return (obj.bidAmount < res.bidAmount) ? obj : res;
});
//Returns {userId: 4, bidAmount: 8100}

How can this be achieved?

0

2 Answers 2

1

You could reduce with an array as result set and check the bidAmount, if it is smaller or equal.

const data = [{userId: 2, bidAmount: 9200}, {userId: 3, bidAmount: 8500}, {userId: 4, bidAmount: 8100}, {userId: 5, bidAmount: 8100}]
var minima = data.reduce((acc, el, index) => {
  if (!index || acc[0].bidAmount > el.bidAmount) return [el];
  if (acc[0].bidAmount === el.bidAmount) acc.push(el);
  return acc;
}, null);

console.log(minima);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Sign up to request clarification or add additional context in comments.

Comments

0

First, get all the bidAmounts in an array. After that, get the indexes of the smallest bidAmount (and store them in indexs). Finally, just get and return the elements by the indexs.

const data = [{userId:2,bidAmount:9200}, {userId:3,bidAmount:8500}, {userId:4,bidAmount:8100}, {userId:5,bidAmount:8100}];

var bidAmounts = data.map(el => el.bidAmount),
    minVal = Math.min(...bidAmounts),
    filteredData = data.filter(dataPoint => dataPoint.bidAmount == minVal);

console.log(filteredData)

5 Comments

You could calculate Math.min(...bidAmounts) before hand instead of doing that in every loop.
I originally did that, but for some reason I removed it - I'm dumb 🙃. Thanks for catching it!
Is there a benefit to doing bidAmounts.forEach( ... ) versus just filtering the data using minVal at this point do you think?
You cannot use filter and return indices. However, I was working on something very similar using reduce, and further lessened the code above using it (it was bothering me for a long time).
I was wondering if the indices were really necessary. Like maybe once you've got minVal, you could just do: data.filter((item) => item.bidAmount === minVal).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.