Filter an array of objects based on specified conditions

My JavaScript object array is structured like this:

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'm looking to filter out objects with description = "10 - 20 Days" and title doesn't include "Grape"

The expected result should be:

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

Answer №1

If you want to easily filter out fruits that have the word "grapes" in their title and a description of "10 - 20 Days", you can achieve this using the Array.protoype.filter method along with the String.prototype.includes function.

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)

Answer №2

To efficiently retrieve specific data, consider employing a filter function similar to this:

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 res = fruits.filter(val=> !val.title.includes('Grape') && val.description.includes('10 - 20 Days'))

console.log(res)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

What are the steps to produce a high-quality WebP image without losing any data?

I recently started experimenting with the WebP image format in Chrome by utilizing the canvas element. After researching on MDN, I discovered that the toDataURL function has a second parameter that determines the quality of the resulting image. My goal is ...

Java program to identify the maximum difference between two consecutive numbers in an array

I'm currently stuck on a homework assignment that involves finding the largest gap between consecutive numbers in an unsorted array. For instance, if we had an array {1,2,3,4,5,20} the gap would be 15. The array I'm working with contains 20 rando ...

When it comes to optimizing JavaScript, what is the best approach for replacing multiple substrings in a string with various strings?

While working on the code I develop and maintain, I encountered an issue. There is a function in my code that takes a query (in the form of a string) and replaces certain substrings within that string with different ones. For instance, if a user inputs th ...

Creating a Universally Unique Identifier in NextJs

I'm currently experimenting with the following code snippet: import { randomUUID } from 'crypto' var id = randomUUID() within my NextJs application, but unfortunately, I encountered the following error: index.js?46cb:369 Uncaught TypeErro ...

How can I access the attributes of items stored in an array in JavaScript?

Input was being retrieved from an HTML text box and stored in an object with multiple properties. Two functions, addAddress and displayAddressDetails, were created for adding data and displaying it. However, there seems to be an issue with displaying the d ...

Is there a problem with page fetching due to the interaction between the history.pushState URL and the jquery

Utilizing the history.pushState function to set a URL, while utilizing jquery's .load method to load page content concurrently. This approach is commonly employed for incorporating back-button functionality in dynamic websites. An issue arises where ...

Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)? var checks = document.querySelectorAll("ul li"); for (var i = 0 ...

When implementing `useRouter().push()` in Next.js, it has the ability to refresh

I have recently started using a custom node server in my Next.js app. Previously, useRouter().push() was working fine without a custom server and providing a seamless single-page app experience. However, with the custom server, it now refreshes my applicat ...

Providing data from a javascript xml file upon page initialization

I am aiming to extract multiple values from an XML file as soon as an HTML page is loaded. The XML file remains constant and will not change over time. It will be stored in the same directory as the HTML page. The purpose of this XML file is to fill severa ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Sorting may produce varied results across various web browsers

function sortResults(type) { $("#parentDiv").empty(); $.getJSON("raw_data.json", ({ Search }) => { Search.sort((a, b) => a[type] > b[type]); console.log(`Sorted by: ${type}`); ...additional code Browser compatib ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

Rails does not accept parameters sent as [object Object] in a GET request

I am having trouble with a GET request to retrieve a single "project". The params I send to Rails are being rejected because they show as [object Object], not the expected params. This method has worked for me in the past, so I'm confused. I should be ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

Typescript error: Unable to instantiate __WEBPACK_IMPORTED_MODULE_1_signature_pad__ as a constructor

Currently, I am working on a project using Angular2 and attempting to incorporate a JS library for signature input from https://github.com/szimek/signature_pad. In my code, I have tried utilizing the library in the following way: // .ts file import * as ...

Enhance user interaction in Angular 13 by animating a selected element using just one animation block

I am currently working on a one-page website project to enhance my Angular skills, and I'm facing a challenge with animating multiple DOM elements using a single animation. Defining the animation for each element individually seems like a cumbersome a ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

Discovering the length of an array in Postgres

When attempting to use array_upper(array(Value)) and array_upper((Value):array[]), I encountered a syntax error. The data type of Value is int []; The expected result is displayed in the table below: Pname week_date Value array_length 5773 ...

Tips for extracting information from the DOM and populating a form with the extracted value

I have a unique identifier defined in both the DOM and another source. The source is located at https://www.example.com/info/data. The data in the above source is displayed below: {"config":{"user_id":"12345"}} The DOM co ...