Reputation: 9844
I have an inventory class. In that class I have 2 functions that have an array of items in them. I want to grab all the items from both arrays and push them together into a singel array which I then use to filter out items.
class Inventory {
private _lions = [];
private _wolves = [];
private _allAnimals: Array<any> = [];
getAllLions(): void {
const lions: Array<ILion> = [
{ id: 1, name: 'Joffrey', gender: Gender.male, age: 20, price: 220, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } },
{ id: 2, name: 'Tommen', gender: Gender.male, age: 18, price: 230, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } },
{ id: 3, name: 'Marcella', gender: Gender.female, age: 24, price: 180, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } },
];
for (let lion of lions) {
this._lions.push(lion);
}
}
getAllWolves(): void {
const wolves: Array<IWolf> = [
{ id: 1, name: 'Jon', gender: Gender.male, price: 130, species: Species.wolf, age: 13, vertrabrates: true, warmBlood: true, hair: 'Grey', runningSpeed: 30, makeSound() { } },
{ id: 2, name: 'Robb', gender: Gender.male, price: 80, species: Species.wolf, age: 18, vertrabrates: true, warmBlood: true, hair: 'Black', runningSpeed: 30, makeSound() { } },
{ id: 3, name: 'Sansa', gender: Gender.female, price: 10, species: Species.wolf, age: 35, vertrabrates: true, warmBlood: true, hair: 'Grey', runningSpeed: 30, makeSound() { } },
{ id: 4, name: 'Arya', gender: Gender.female, price: 190, species: Species.wolf, age: 8, vertrabrates: true, warmBlood: true, hair: 'White', runningSpeed: 30, makeSound() { } },
];
for (let wolf of wolves) {
this._wolves.push(wolf);
}
}
getAllAnimals(): void {
this._allAnimals = this._lions.concat(this._wolves);
};
findByTemplate(template: any): Array<any> {
return this._allAnimals.filter(animal => {
return Object.keys(template).every(propertyName => animal[propertyName] === template[propertyName]);
});
}
}
Doing to for loop on the array for lions and wolves works, but I would rather push the whole array in the field. But then I'm pushing an array inside an array which causes problems with the filter function.
Is it possible to push the lion array into the _lion field witout inserting an array in an array?
Upvotes: 0
Views: 680
Reputation: 112
With the spread operator you can do it using push, like:
this._wolves.push(...wolves);
Upvotes: 2
Reputation: 9844
It seems that:
this._wolves = this._wolves.concat(wolves);
Is a good solution, with concat it grabs the all the objects from an array to merge them with another array. But if you don't do that it just returns the objects from the current array.
Upvotes: 0