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.

2
  • 1
    Use the for, luke. Commented Oct 7, 2013 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. Commented Oct 7, 2013 at 12:20

5 Answers 5

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@tymeJV, could you show a working example like in jsfiddle? Doesn't work for me
4

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];
}

Comments

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.

7 Comments

For a total newbie, a simple and more compatible for loop is probably more advisable.
@dystroy, I do not agree. Do you want to clarify why you think that way?
@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).
@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! :)
@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?
|
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.

Comments

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.