Filter an array in Javascript based on multiple conditions

I am working with an array that looks like this:

var arr = 
[
    {
        "id":3,
        "first_name":"Laila",
        "last_name":"McCaine",
        "gender":"female",      
        "populations":[{"population_name":"Heart failure"}, {"population_name":"AMI"}],
        "score": 55.0
    },
    {
        "id":5,     
        "first_name":"Riva",
        "last_name":"Rontgen",
        "gender":"female",
        "populations":[{"population_name":"Pnumonia"}],
        "score": 85.0
    },
    {
        "id":8,
        "first_name":"Emily",   
        "last_name":"Rosewood",
        "gender":"female",  
        "populations":[],
        "score": 25.0
    }
];

Additionally, I have the following variables defined:

var score='';
var population='';
var status = '';

Now, I need to use the filter function on the array with multiple conditions such as Find records where the score is less than 40, status equals 1, and population_name is "heart failure".

The challenge here is that these three variables are dynamic, and the filter should only be applied if their values are not empty.

How can I achieve this?

Answer №1

Here's an example of how you could write this:

arr.filter(function(element) {
    var valid = true;

    if (grade !== '') {
        valid = element.grade < grade;
    }

    if (valid && population !== '') {
        // check population
        valid = element.populations.map(function() {return element.population_name;}).indexOf(population) > -1;
    }

    if (valid && status !== '') {
        // check status
    }

    return valid;
});

Answer №2

var data = 
[
    {
        "id":3,
        "status": 1,
        "first_name":"Laila",
        "last_name":"McCaine",
        "gender":"female",      
        "populations":[{"population_name":"Heart failure"}, {"population_name":"AMI"}],
        "score": 55.0
    },
    {
        "id":5,   
        "status": 1,
        "first_name":"Riva",
        "last_name":"Rontgen",
        "gender":"female",
        "populations":[{"population_name":"Pneumonia"}],
        "score": 85.0
    },
    {
        "id":8,
        "status": 0,
        "first_name":"Emily",   
        "last_name":"Rosewood",
        "gender":"female",  
        "populations":[],
        "score": 25.0
    }
];

function filterData( data ){
  return data.filter(function( entry ){
    return entry.score > 40 && entry.status && (entry.populations.filter(function( population ){
      return population.population_name == 'Heart failure';
    })).length;
  });
}

console.log( filterData( data ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

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

Running JavaScript code on a webpage using Selenium

I'm currently developing an automated script to enter a person's address details on a webpage. It's important to note that I did not create this webpage myself. While filling in the address details, I encountered an option to select the coun ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

Create a separate mongoose schema for every element in an array by utilizing ecmascript 6

After traversing an array, I create a new mongoose schema by adding two fields and then saving it. myArray.forEach(email => { const newUsers = new UserList({ email, uuid: uuidv4() }); newUsers.save().catch(err => console ...

Error encountered in React JS: The property being accessed is undefined and therefore cannot be mapped

I have been working on a MERN project and I am currently at the stage where I am integrating the frontend and backend using Axios. However, I have encountered some issues. One of the most common errors I am facing in my list screens is: TypeError: Cannot r ...

Guide on adding a new member to Mailchimp through node.js and express

Hello, I've been delving into working with APIs, particularly the mail-chimp API. However, I've encountered a problem that has me stuck: const express=require("express"); const bodyparser=require("body-parser"); const request=require("request" ...

Creating a proxy for an HTTP video stream (from VLC) using NodeJS and ExpressJS

Using VLC 2.2.1, I am able to create an HTTP stream of my webcam from a computer named server. If I open VLC on another computer, client, and enter the network stream http://server:8080, the webcam video displays perfectly. A Wireshark capture of the HTT ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Guide on retrieving JSON information through an AJAX request within an AngularJS Bootstrap modal

I am eager to implement the following functionality: a button that triggers a dialog/modal from Angular Bootstrap which showcases a loading indicator as the application retrieves JSON data from the server. Once the data is fetched, it should be displayed w ...

What is the best way to transfer an array from a C# function to VBA?

Is there a way to transfer an array from a C# function to VBA? Is it possible to achieve this transfer? ...

What is the best way to accomplish this task with promises (using the Q library)?

I am currently working on an app using express.js and mongodb. My goal is to fetch all posts if the database is available, otherwise an error will be thrown. I am utilizing the Q package for promises, but I am struggling to implement the desired functional ...

Events are not being triggered when using node busboy with express 4 and ng-file-upload

I am currently utilizing the mean.io stack along with ng-file-upload module. Does anyone have any insights as to why the events are not being triggered? Your assistance would be greatly appreciated. Client controller('ArticleParentCtrl', [&apo ...

An unusual combination of '||' and '&&' occurred while utilizing babel

I've encountered an issue while building and publishing a package on npm with babel. The build process is showing me the following warning: Line 1: 'use strict' is unnecessary inside of modules strict Line 23: Unexpected mix of '| ...

Setting up various connections is made possible through Node.js Socket.io

In the process of developing a straightforward chat application using socket.io and incorporating passport.js for user authentication, an issue arises when users log out and then back in. The previous socket connection remains active, resulting in two conn ...

Ways to access data stored in the browser's local storage

I have a unique reminder app that stores user inputs in local storage and then displays them on a different page within the app. The process of storing these values in local storage is done through this code snippet: <h2 style="text-align:center;margin ...

React-select allows for multiple selections within a component when the onChange function

I am currently utilizing react-select. Per the official documentation, it recommends using 'isMulti' to select more than one option. Below is the custom component that I have created. import React from 'react'; import { Form } from &ap ...

Switch between player and computer turns in a card game created with react.js

Imagine a hearts card game with 4 players, who play in an anticlockwise direction: p1 -> p2 -> p3 -> p4. If p3 is the first to play, select cards for p3 and p4, then wait for the user to select a card before moving on to p2. If p4 starts, choos ...

Issue with adding dynamic keys to state in Next.js using Zustand for state management not resolving

I've been experimenting with dynamically adding a key to a state in zustand. I've attempted various methods such as 1. const store = (set, get) => ({ keyAttrib: {key1: "value1", key2: 2}, update: (key, value) => { let new ...