Nickon
Nickon

Reputation: 10146

Get max value in JS for filtered array of objects

I have an array of objects like:

var myArr = [{
    number: 5,
    shouldBeCounted: true
}, {
    number: 6,
    shouldBeCounted: true
}, {
    number: 7,
    shouldBeCounted: false
}, ...];

How to find max number for objects with shouldBeCounted set to true? I don't want to use loops, just wondering if this is possible with Math.max.apply (or something like this).

Upvotes: 0

Views: 1077

Answers (5)

dazn311
dazn311

Reputation: 161

if you only need to get the number, then you can try:

let myArr = [
  { number: 5, shouldBeCounted: true},
  { number: 6, shouldBeCounted: true},
  { number: 7, shouldBeCounted: false}
];

function maxNum(mArr) {
  return  Math.max(...mArr.filter(a => a.shouldBeCounted ).map( o => o.number))
}
console.log(maxNum(myArr))

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

With a simple .reduce():

var myArr = [{
  number: 5,
  shouldBeCounted: true
}, {
  number: 6,
  shouldBeCounted: true
}, {
  number: 7,
  shouldBeCounted: false
}];

var max = myArr.reduce(function(max, current) {
  return current.shouldBeCounted ? Math.max(max, current.number) : max;
}, -Infinity);

console.log(max);

Where

  • myArr.reduce() - Reduces an array to a single value. Accepts a function with two parameters, the current cumulative value, and the current item (also two more optional parameters for the index of the item, and the original array).
  • return current.shouldBeCounted ? Math.max(max, current.number) : max; - For each item, returns the current max is shouldBeCounted is false, or the max between the current known max and the current number.
  • , -Infinit - Starting with -Infinity.

The advantage of this approach over the one in the accepted answer is that this will only iterate the array once, while .filter() and .map() loop over the array once each.

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382102

Another less verbose solution (if your numbers are all positive):

var max = Math.max.apply(Math, myArr.map(function(el) {
    return el.number*el.shouldBeCounted;
}));

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

No it's not possible. You can use Math.max with .map like so

var myArr = [{
    number: 5,
    shouldBeCounted: true
}, {
    number: 6,
    shouldBeCounted: true
}, {
    number: 7,
    shouldBeCounted: false
}];


var max = Math.max.apply(Math, myArr.map(function (el) {
    if (el.shouldBeCounted) {
        return el.number;
    }
    
    return -Infinity;
}));

console.log(max);

Upvotes: 5

Jose Mato
Jose Mato

Reputation: 2799

You can't. All solutions require walk the array unless you will be storing max number in a variable before adding to the array.

Upvotes: 0

Related Questions