Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function to push constructor objects with the same property to an array

If I make a list of objects as follows:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

var car1 = new Car('eagle', 'Talon TSi', 1993, 'rand');
var car2 = new Car('nissan', '300ZX', 1992, 'ken');
var car3 = new Car('nissan', '54353', 2001, 'barbie');
var car4 = new Car('nissan', 'XT', 2012, 'sam');
var car5 = new Car('eagle', 'GT', 2011, 'owen');
var car6 = new Car('eagle', '9', 2014, 'finn');

How can I push all objects with the same make to an array that I name, eg:

var nissan = [];
var eagle = [];

Or even better naming the array after the make without having to declare that line of code.

like image 472
Nick_O Avatar asked May 23 '26 04:05

Nick_O


1 Answers

Use an array instead of car1, car2, car3, etc. This allows you to call Array#filter on the result and get a list of cars with a certain make only:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

var cars = [
  new Car('eagle', 'Talon TSi', 1993, 'rand'),
  new Car('nissan', '300ZX', 1992, 'ken'),
  new Car('nissan', '54353', 2001, 'barbie'),
  new Car('nissan', 'XT', 2012, 'sam'),
  new Car('eagle', 'GT', 2011, 'owen'),
  new Car('eagle', '9', 2014, 'finn')
]

function isMake (car) {
  return car.make === String(this)
}

var nissans = cars.filter(isMake, 'nissan')
var eagles = cars.filter(isMake, 'eagle')

console.log(nissans)
console.log(eagles)
.as-console-wrapper { min-height: 100vh; }

Edit: As bejado points out in his answer, you probably meant to use quotes for the owners of your car. I had assumed they were objects representing people.

like image 144
gyre Avatar answered May 24 '26 18:05

gyre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!