newbie here.
I'm having trouble with a simple challenge, the goal is simple, push the sedan cars into another array, so the output when the function is called (no console.log can be used, it will be ignored) is:
[ { type:'sedan', size: 'white'} , { type:'sedan', color:'red'} ].
The suggestion is to use push().
Here is my terrible code.
Any help is welcome!
function filterCars (cars) {
const sedanCars = []
const carArr = [
{ type: 'sedan', color: 'white'},
{ type: 'truck', color: 'blue'},
{ type: 'sedan', color: 'red'},
{ type: 'coupe', color: 'red'}
]
var arrayLength = carArr.length;
for (var i = 0; i < arrayLength; i ) {
console.log(carArr[i]);
if(carArr.type==="sedan") {
return sedanCars.push("sedan");
}
CodePudding user response:
I guess the cars
arg is the one containing the cars you want to iterate.
function filterCars(cars) {
const sedanCars = []
const arrayLength = cars.length;
for (let i = 0; i < arrayLength; i ) {
if (cars[i].type === "sedan") sedanCars.push(cars[i]);
}
return sedanCars
}
The return
statement should be at the end of the function
.
If is inside the for will break;
the function.
CodePudding user response:
Since push
is only a suggestion, I would recommend a more modern approach using the array filter
method for this:
const cars = [
{ type: 'sedan', color: 'white'},
{ type: 'truck', color: 'blue'},
{ type: 'sedan', color: 'red'},
{ type: 'coupe', color: 'red'},
];
const sedans = cars.filter(car => car.type === 'sedan');
The filter
methods takes a callback function that is called on each element of the array. If it returns a truthy value then that item will be included in the resulting array.
Read more about filter on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
CodePudding user response:
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.
This may be what you're looking for:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If you really prefer to use push()
here is another method:
const sedanCars = [];
const 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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>