kai0 kai0 - 1 month ago 25
Javascript Question

How to find right properties in the array with obejcts(arrange by age)?

Declare massive with objects and console log the different people according to their Age.



var people = [
{ firstname: 'Gosho', lastname: 'Petrov', age: 42 },
{ firstname: 'Bay', lastname: 'Ivan', age: 81 },
{ firstname: 'John', lastname: 'Doe', age: 42 },
{ firstname: 'Pesho', lastname: 'Pesho', age: 22 },
{ firstname: 'Asdf', lastname: 'Xyz', age: 81 },
{ firstname: 'Gosho', lastname: 'Gosho', age: 22 }
];


var counter=0;
for(i=0; i<people.lenght; i+=1) {
if (people[i].age === people[i+1].age) {
counter+=people[i];
}
}


How can i arrange the people by Age and console log them.

Answer

You could use Array#sort.

var people = [{ firstname: 'Gosho', lastname: 'Petrov', age: 42 }, { firstname: 'Bay', lastname: 'Ivan', age: 81 }, { firstname: 'John', lastname: 'Doe', age: 42 }, { firstname: 'Pesho', lastname: 'Pesho', age: 22 }, { firstname: 'Asdf', lastname: 'Xyz', age: 81 }, { firstname: 'Gosho', lastname: 'Gosho', age: 22 }];

people.sort(function (a, b) {
    return a.age - b.age; // ascending
});

console.log(people);
.as-console-wrapper { max-height: 100% !important; top: 0; }