How can I return a target object from an array based on two properties, one which requires min/max and the other, in this case, is a boolean?
For example, in the below array, I'd like to return the object with the smallest order
attribute and whose isComplete
is false
.
var a = [
{
order: 3,
isComplete: false,
name: 'A',
},
{
order: 2,
isComplete: false,
name: 'B',
},
{
order: 1,
isComplete: true,
name: 'C',
},
{
order: 4,
isComplete: false,
name: 'D',
},
{
order: 5,
isComplete: false,
name: 'E',
},
];
If I check for order
attribute, reduce
correctly returns smallest object:
var r = a.reduce((prev, curr) => {
return (
prev.order < curr.order
) ? prev : curr;
});
// CORRECT Output: {order: 1, isComplete: true, name: "C"}
However, if I also want to return the one with isComplete
as false
, Order 4
is incorrectly returned. Expected is the next smallest Order 2
to be returned:
var r = a.reduce((prev, curr) => {
return (
prev.order < curr.order
&&
!prev.isComplete
) ? prev : curr;
});
// INCORRECT Output: {order: 4, isComplete: false, name: "D"}
// EXPECTED Output: {order: 2, isComplete: false, name: "B"}
I'm assuming reduce
will not work for what I'm trying to do.
One way I can think of is to pre-filter on the other attributes and then sort, but this doesn't seem optimal:
var r = a.filter(el => !el.isComplete).reduce((prev, curr) => {
return (
prev.order < curr.order
) ? prev : curr;
});
// CORRECT Output: {order: 2, isComplete: false, name: "B"}