2

I want to iterate over an array of objects in order to get the oldest person and the youngest person. How could I get that? It looks like an easy task, but there is no way I can get the ages with simple for each loop. Any ideas?

var p = [
    { name : "Billy", age : 5 },
    { name : "Lucy", age : 31 },
    { name : "Jonny", age : 11 },
    { name : "Wolfgang", age : 78 },
    { name : "Robert", age : 23 }
];

I have seen this but it didn't help me in understanding the problem.

Community
  • 1
  • 1
Kanan Farzali
  • 991
  • 13
  • 23
  • 1
    [Use the for, luke](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). – Denys Séguret Oct 07 '13 at 12:20
  • Try having two pointers MIN and MAX. With each comparison in the loop compare these values with the current value. By the end of the loop you will have both the required values. – Dhrubajyoti Gogoi Oct 07 '13 at 12:20

5 Answers5

6

Simple for loop

var high = 0,
    low;

//Start at 0 index, iterate until the array length, iterate by 1
for (var i = 0; i < p.length; i++) {
    //checking high
    if (p[i].age > high)
        high = p[i].age;

    //checking low
    if (p[i].age < low || low == null)
        low = p[i].age;
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    If you set `high` to `p[0].age` and `low` to `p[0].age` and then `i` to 1 in the start of the loop you wouldn't have to worry about checking if `low` is `null`. – h2ooooooo Oct 07 '13 at 12:24
  • @tymeJV, could you show a working example like in jsfiddle? Doesn't work for me – Kanan Farzali Oct 07 '13 at 12:29
3

You can use a for in loop to solve this. The only thing you need to remember that the loop will give you only the index. Therefore you need to access the original object.

A possible solution is:

var maxPerson = p[0];

for(var i in p) {
    if (p[i].age > maxPerson.age)
        maxPerson = p[i];
}
Markus
  • 192
  • 6
2

To iterate over array in JavaScript, you use .forEach.

p.forEach(function(person){
    console.log(person.name + ' is ' + person.age + ' years old.');
});

Note that .forEach is not supported in IE 8 and below. You can use es5-shim to add that functionality to old browsers, or use jQuery each if you already use jQuery anyway.

Now to get the oldest and the youngest we need to store the best choices as we loop over the list (jsFiddle):

var oldest = p[0];
var youngest = p[0];
p.forEach(function(person){
    if (oldest.age < person.age) { oldest = person; }
    if (person.age < youngest.age) { youngest = person; }
});

In the end, oldest and youngest will contain the appropriate objects.

Denis
  • 5,061
  • 1
  • 20
  • 22
  • For a total newbie, a simple and more compatible for loop is probably more advisable. – Denys Séguret Oct 07 '13 at 12:21
  • @dystroy, I do not agree. Do you want to clarify why you think that way? – Denis Oct 07 '13 at 12:22
  • @Denis I mean the basic flow control structures are among what the basic knowledge any programmer should have before delving into advanced features (especially when it means worrying about compatibility and shims). – Denys Séguret Oct 07 '13 at 12:24
  • @dystroy, a function is a basic flow control in JavaScript, because it is mainly a functional language. A syntax of `for` loop is cryptic, to say the least! :) – Denis Oct 07 '13 at 12:26
  • @Denis, could you provide a jsfiddle? It doesn't work on Chrome latest either for me. – Kanan Farzali Oct 07 '13 at 12:26
  • 1
    @KananFarzali You're probably copy pasting directly from OP where `"`'s are `“` and `”`'s instead. Have you copied this from a wordpress blog or somewhere else where they nice-ify quotes? – h2ooooooo Oct 07 '13 at 12:33
  • @Denis, good stuff. Don't understand why it didn't work for me, probably too hungry lol. Thanks! – Kanan Farzali Oct 07 '13 at 12:36
1

If you want to retrieve only two objects, the oldest and the youngest, then the easiest way would be to sort the array in either ascending or descending order based on age, then take the first and last elements of the resulting array.

Community
  • 1
  • 1
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
1

Using sort (mdn doc) will work in every browser :

p.sort(function (a, b) {
    return a.age - b.age;
});

var youngest = p[0];
var oldest = p[p.length - 1];

Be careful however, sort modifies the original array. You may clone it in order to bypass this issue :

var clone = [].concat(p).sort(/* compare function */);
var youngest = clone[0];
var oldest = clone[clone.length - 1];