2

I wants to find out the object which holds the smallest value of a key in an array.

var tempArr = [{name: 'john', age: 23}, {name: 'jonny', age: 27}, {name: 'roony', age: 13}, {name: 'david', age: 33}];

I want the result to be

{name: 'roony', age: 13}

without using for loop is there any direct way to find out the result, like we can do for plain array

for example: if array is -

var arr = [11,4,22,3,5,55];

we can achieve the same by:

Math.min.apply(null, arr)
robieee
  • 364
  • 2
  • 18
  • 2
    Use `sort()` or `map()` and why are your numbers strings? – epascarello Jan 15 '15 at 18:15
  • @epascarello: sorry typo mistake, they are numbers. do sort method works with the array containing objects ? – robieee Jan 15 '15 at 18:16
  • Here's the detail you need to make it work @robieee http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript – Mic Jan 15 '15 at 18:17
  • Why don't you want to use a for loop? – Daniel Robinson Jan 15 '15 at 18:22
  • @DanielRobinson: There are many good reasons to avoid `for`-loops. Chief among then is the fact that they do little to express programmer intent, focusing instead on mostly irrelevant bookkeeping instructions to the computer. This video explains fairly well: http://vimeo.com/43382919 – Scott Sauyet Jan 15 '15 at 18:58
  • 1
    In many cases, I would agree. But for this example, compare how it would be done with a `for` loop to my answer below that uses `reduce`. Is the latter really that much less concerned with irrelevant bookkeeping? – Daniel Robinson Jan 15 '15 at 19:03

3 Answers3

7

You should use reduce:

min = tempArr.reduce(function(previousValue, currentValue, index, array) {
    return (currentValue.age < previousValue.age ? currentValue : previousValue);
});

Any solution involving sort will be suboptimal.

Daniel Robinson
  • 3,347
  • 2
  • 18
  • 20
3

@antyrat's solution is more explicit, but I figured I'd provide another way:

var people=[{name: 'john', age: 23}, {name: 'jonny', age: 27}, {name: 'roony', age: 13}, {name: 'david', age: 33}];

var youngestPerson = people.reduce(function(youngestPerson, person){
    return person.age < youngestPerson.age ? person : youngestPerson; 
}, people[0]);

console.log(youngestPerson);
Max Heiber
  • 14,346
  • 12
  • 59
  • 97
0

Yes, you can use sort method:

var tempArr = [{name: 'john', age: '23'}, {name: 'jonny', age: '27'}, {name: 'roony', age: '13'}, {name: 'david', age: '33'}];
tempArr = tempArr.sort( function( a, b ) {
    var AgeA = parseInt( a.age, 10 );
    var AgeB = parseInt( b.age, 10 )
    if ( AgeA < AgeB ) return -1;
    else if ( AgeA > AgeB ) return 1;
    else return 0;
});
console.log(tempArr);
console.log(tempArr[0]); // is the record with smallest `age` value
antyrat
  • 27,479
  • 9
  • 75
  • 76