Your filterCars function and return do not seem all that clear to me in their function, especially since you are triggering your return within a for loop iteration.
There are several ways we can approach this…
Option #1. Building a filter-based function
function getSedans(cars) {
return cars.filter(car => car.type === 'sedan')
}
const carArr = [
{ type: 'sedan', color: 'white' },
{ type: 'truck', color: 'blue' },
{ type: 'sedan', color: 'red' },
{ type: 'coupe', color: 'red' }
];
const sedanCars = getSedans(carArr);
// including this console.log to provide the output
console.log(sedanCars);
Option #2. filter-based function + push() & spread (...)
If you would prefer to use this solution but also use push, you could do by declaring the empty sedanCars array before the carArr and then push the results of getSedans(carArr) to it like this…
const sedanCars = [],
carArr = [ /* cars here */ ];
sedanCars.push(...getSedans(carArr));
You can see that in action here:
function getSedans(cars) {
return cars.filter(car => car.type === 'sedan')
}
const sedanCars = [],
carArr = [
{ type: 'sedan', color: 'white' },
{ type: 'truck', color: 'blue' },
{ type: 'sedan', color: 'red' },
{ type: 'coupe', color: 'red' }
];
sedanCars.push(...getSedans(carArr));
// including this console.log to provide the output
console.log(sedanCars);
Option #3. push() method using for..of loop
However, this adds an extra unnecessary step by using spread. If you really prefer to use push(), here is a more appropriate method for using it:
const sedanCars = [],
carArr = [
{ type: 'sedan', color: 'white' },
{ type: 'truck', color: 'blue' },
{ type: 'sedan', color: 'red' },
{ type: 'coupe', color: 'red' }
];
for (const car of carArr) {
if (car.type === 'sedan') sedanCars.push(car);
}
// including this console.log to provide the output
console.log(sedanCars);
Option #4. push() method using forEach method
And lastly, if you wanna get fancy, you could replace that entire for..of loop with a forEach invocation and replace the if statement for a short circuit, like this:
carArr.forEach(car => car.type === 'sedan' && sedanCars.push(car));
Here is how that would look in action:
const sedanCars = [],
carArr = [
{ type: 'sedan', color: 'white' },
{ type: 'truck', color: 'blue' },
{ type: 'sedan', color: 'red' },
{ type: 'coupe', color: 'red' }
];
carArr.forEach(car => car.type === 'sedan' && sedanCars.push(car));
// including this console.log to provide the output
console.log(sedanCars);
carArris an array, not an object. You need to index it to access the object with atypeproperty.push()method, and another using thespreadoperator (...).