1

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.

Community
  • 1
  • 1
kai0
  • 47
  • 8

2 Answers2

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use Lodash sortBy() method.

https://lodash.com/docs#sortBy

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, [function(o) { return o.age; }]);

this will returns sorted new array

[['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
vistajess
  • 667
  • 1
  • 8
  • 23