0

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 }

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Athfan
  • 125
  • 8
  • 1
    [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Write a title that **summarizes the specific problem**"_ – Andreas Nov 13 '21 at 11:21
  • The first step when a built-in method doesn't work as "expected" -> Read the documentation: [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): _"The `filter()` method **creates a new array** with all elements that pass the test implemented by the provided function."_ – Andreas Nov 13 '21 at 11:23
  • `filter()` doesn't modify the input, but returns a new array. – tevemadar Nov 13 '21 at 11:23

3 Answers3

1

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;
        }
});
DevZer0
  • 13,433
  • 7
  • 27
  • 51
1

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);
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

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)