I have an array that contains multiple objects, which i'm trying to add to another larger array with more objects in it. I'm wondering how I can automatically assign their position based on a property that each object shares. Example:
function person(name, age) {
this.name = name;
this.age = age;
}
function pet(name, age) {
this.name = name;
this.age = age;
}
var person1 = new person("Amanda", 25);
var person2 = new person("Jack", 29);
var pet1 = new pet("Fluffy", 4);
var pet2 = new pet("Spaz", 5);
personArray = [person1, person2];
petArray = [pet1, pet2];
In the example I would like to combine the personArray and petArray into a new array using the age property of each to sort them into the array by order of youngest to oldest. Any help is appreciated.
concat()
and sort()
will get you there:
var mixedArray = personArray.concat(petArray).sort(
function (a, b) {
return a.age - b.age;
}
);
Results in:
[
{
"name": "Fluffy",
"age": 4
},
{
"name": "Spaz",
"age": 5
},
{
"name": "Amanda",
"age": 25
},
{
"name": "Jack",
"age": 29
}
]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments