array, foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
and here's what I tried,
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
function removeRed(food) {
food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
return foods;
When I call the function like " removeRed(foods) " the output is giving both of the property-value pairs in my array. I'm a beginner student and this is my first Question here. Hope that someone answers :'D }
you need to return the output of the filter. you were returning the original array
function removeRed(food) {
return food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
Put return inside the function before the filter called
function removeRed(food) {
return food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
}
Call the function to execute the code
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
removeRed(foods); // [{name: 'Egg', color: 'white'}]
Best practice Make always the function more generic like this:
function remove(food, color) {
return food.filter(function (x) {
if (x.color !== color) {
return true;
} else {
return false;
}
});
}
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
remove(foods,'white'); // [{name: 'Apple', color: 'red'}]
One line with ES6+ syntax:
const remove = (food, color) => food.filter(x=> x.color !== color);
Use this code to filter non-red items
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
const filtered = foods.filter(item => item.color !== 'red');
console.log(filtered)