2

I have an array like this

     var data = [
      { i: 0, j: 0, day: 5 },
      { i: 1, j: 0, day: 3 },
      { i: 1, j: 1, day: 5 },
      { i: 1, j: 2, day: 10 },
      { i: 2, j: 0, day: 5 },
      { i: 3, j: 0, day: 5 },
      { i: 4, j: 0, day: 6 },
      { i: 4, j: 1, day: 10 }
    ]

I want to return a single row from JSON with minimum day value

For eg in the above array minimum day is 3 and i want to get

{ i: 1, j: 0, day: 3 } 

as output

I have tried this method

Math.min.apply(Math,data.map(function(item){return item.day})) but it returns only the minimum day

One solution i found is using indexOf method but i don't think its a good practice. Is there any shorthand method ??

SabirAmeen
  • 153
  • 9
Jabaa
  • 1,743
  • 7
  • 31
  • 60

1 Answers1

6

You could use Array#reduce and return the element with the smaller day property.

For empty arrays, you need a check in advance, because

Calling reduce on an empty array without an initial value is an error.

var data = [{ i: 0, j: 0, day: 5 }, { i: 1, j: 0, day: 3 }, { i: 1, j: 1, day: 5 }, { i: 1, j: 2, day: 10 }, { i: 2, j: 0, day: 5 }, { i: 3, j: 0, day: 5 }, { i: 4, j: 0, day: 6 }, { i: 4, j: 1, day: 10 }],
    result = data.reduce(function (a, b) {
        return a.day < b.day ? a : b;
    });
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392