Numbersgame
Numbersgame

Reputation: 13

Combine multiple arrays containing objects using object property values

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.

Upvotes: 0

Views: 64

Answers (3)

Alex W
Alex W

Reputation: 38173

You can easily do it with the built-in Array.sort function. You would just have to check what properties the object has and then the age. Your objects, in your example, are very similar to the example on MDN:

var items = [
  { name: "Edward", age: 21 },
  { name: "Sharpe", age: 37 },
  { name: "And", age: 45 },
  { name: "The", age: 12 },
  { name: "Magnetic" },
  { name: "Zeros", age: 37 }
];
items.sort(function (a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    // a must be equal to b
    return 0;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95508

You can use Array.sort with a custom comparator-function:

var mixedSortedArray = personArray.concat(petArray).sort(function(a, b) {
    return a.age - b.age;
});

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

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

Upvotes: 1

Related Questions