Iḿ trying to run through an array with object to get different results as part of an excercise for our IT Bootcamp. I just can´t seem to get it working. First here is the task.
Create an array of cars. The cars are objects and they have the properties: brand, price, horsepower, color and year_of_construction. Create following cars there:
* `BMW(70000, 200hp, white, 2020)`
* `Mazda(45000, 220hp, silver, 2021)`
* `Volvo(55000, 190hp, beige, 2021)`
* `Opel(38000, 155hp, black, 2021)`
* `Mazda(22000, 90hp, magenta, 2021)`
* `Fiat(19000, 110hp, blue, 2019)`
* Create a loop which filters all cars which cost less than `60000` (means print all properties).
* Create a loop which filters all cars which have more than `150 hp`.
* Create a loop which will print all cars that are made after `2020` and have less than `100 hp`.
* Create a loop which will print all cars that are by `Fiat` or have less than `150 hp`.
Now my code, I can access different indexes in the array, but if I run the code with the loop at the end the console just says (0=)[].
Please help me, somerwhere I don´t get the logic
`
let cars = [
{
Brand: "BMW",
price: 70000,
horsePower: 200,
color: "white",
yearOfConstruction: 2020,
},
{
Brand: "Mazda",
price: 45000,
horsePower: 220,
color: "silver",
yearOfConstruction: 2021,
},
{
Brand: "Volvo",
price: 55000,
horsePower: 190,
color: "beige",
yearOfConstruction: 2021,
},
{
Brand: "Opel",
price: 38000,
horsePower: 155,
color: "black",
yearOfConstruction: 2021,
},
{
Brand: "Mazda",
price: 22000,
horsePower: 90,
color: "magenta",
yearOfConstruction: 2021,
},
{
Brand: "Fiat",
price: 19000,
horsePower: 110,
color: "blue",
yearOfConstruction: 2019,
},
];
let newCars = [];
for (let i=1; i<= cars.lenght; i ){
if (cars[i].price < 60000){
newCars.push(cars[i]);
}
}
console.log(newCars);
`
Thanks for your help.
I tried looking for a solution but we should just use loops and every solution I found uses functions.
CodePudding user response:
There are a few things going on here:
- You need to start iterating from 0 rather than 1
- You have a spelling error
cars.lenght
should becars.length
- As @wendt88 pointed out in the comments, it should be
< cars.length
not<=
I recommend you use a VS Code with the Code Spell extension - it will point out spelling errors for you.
FYI, you can also do this exercise using Array.prototype.filter:
const newCars = cars.filter(car => car.price < 60000)
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
CodePudding user response:
let filter1 = cars.filter(car => car.price < 60000); console.log(filter1);
let filter2 = cars.filter(car => car.horsePower > 150); console.log(filter2)
let filter3 = cars.filter(car => car.yearOfConstruction > 20 && car.horsePower < 100); console.log(filter3);
let filter4 = cars.filter(car => car.Brand === "Fiat" || car.horsePower < 150); console.log(filter4);