Search code examples
javascriptarraysjavascript-objects

Filter array of object with conditional statement


I have JavaScript object array with the following structure:

const fruits =       [{
                        "id": "1",
                        "title": "Banana",
                        "description": "1 Minute"
                    },
                    {
                        "id": "2",
                        "title": "Apple",
                        "description": "2 - 3 Days"
                    },
                    {
                        "id": "3",
                        "title": "Manggo",
                        "description": "10 - 20 Days"
                    },
                    {
                        "id": "4",
                        "title": "Orange",
                        "description": "10 - 20 Days"
                    },
                    {
                        "id": "5",
                        "title": "Grape blue",
                        "description": "10 - 20 Days"
                    },
                    {
                        "id": "6",
                        "title": "Grape red",
                        "description": "10 - 20 Days"
                    }]

I want to extract object which has description = "10 - 20 Days" and title not contains "Grape"

Then my expected should be

                    {
                        "id": "3",
                        "title": "Manggo",
                        "description": "10 - 20 Days"
                    },
                    {
                        "id": "4",
                        "title": "Orange",
                        "description": "10 - 20 Days"
                    }

Solution

  • This is very simple to do by using Array.protoype.filter. Within the filter callback, you can use String.protoype.includes method to check if the title includes "grapes":

    const fruits = [{
        "id": "1",
        "title": "Banana",
        "description": "1 Minute"
      },
      {
        "id": "2",
        "title": "Apple",
        "description": "2 - 3 Days"
      },
      {
        "id": "3",
        "title": "Manggo",
        "description": "10 - 20 Days"
      },
      {
        "id": "4",
        "title": "Orange",
        "description": "10 - 20 Days"
      },
      {
        "id": "5",
        "title": "Grape blue",
        "description": "10 - 20 Days"
      },
      {
        "id": "6",
        "title": "Grape red",
        "description": "10 - 20 Days"
      }
    ];
    
    const filteredFruits = fruits.filter(fruit => {
      if (!fruit.title.toLowerCase().includes("grape")) {
        if (fruit.description === "10 - 20 Days") {
          return true;
        }
      }
    
      return false;
    });
    
    console.dir(filteredFruits)