How can you iteratively filter an array using JavaScript?

My goal is to create a function that can filter an array based on one or multiple conditions.

Let's examine this example data and filter criteria:

var data = [
  {company: "Acme", fiscal_period: '01-2019', value: 10},
  {company: "Acme", fiscal_period: '02-2019', value: 15},
  {company: "Wonka", fiscal_period: '01-2019', value: 8},
  {company: "Wonka", fiscal_period: '02-2019', value: 11}
]

var filter = [{field: "company", value: "Acme"}]
console.log(myFilterFunction(data,filter));
// Expected result 
// [
//   {company: "Acme", fiscal_period: '01-2019', value: 10},
//   {company: "Acme", fiscal_period: '02-2019', value: 15}
// ]

// Now let's use two filters:
var filter = [{field: "company", value: "Acme"},{field: "fiscal_period", value: "01-2019"}]
console.log(myFilterFunction(data,filter);
// Expected result 
// [
//   {company: "Acme", fiscal_period: '01-2019', value: 10},
// ]

The question now is how to implement the myFilterFunction?

I understand how it works with a single static filter:

myFilterFunction = function(data,filter){

  return data.filter(function(el){
    return el[filter.field] === filter.value;
  });

}

console.log(myFilterFunction(data,{field: "company", value: "Acme"});

But I am unsure how to make it dynamic when dealing with multiple filters.

Answer №1

Utilize an array to pass multiple field data and apply the Array#every method to validate all filters, returning true only if all values are true.

myFilterFunction = function(data, filters){    
  return data.filter(function(el){
    return filters.every(filter => el[filter.field] === filter.value);
  });    
}

console.log(myFilterFunction(data, [{field: "company", value: "Acme"}, {field: "value", value: 10}]));

var data = [{
    company: "Acme",
    fiscal_period: '01-2019',
    value: 10
  },
  {
    company: "Acme",
    fiscal_period: '02-2019',
    value: 15
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 8
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 11
  }
]

myFilterFunction = function(data, filters) {
  return data.filter(function(el) {
    return filters.every(filter => el[filter.field] === filter.value);
  });
}

console.log(myFilterFunction(data, [{field: "company", value: "Acme"}, {field: "value", value: 10}]));

Using ES6 Destructuring parameter and arrow function.

myFilterFunction = (data, filters) => {    
  return data.filter(el => filters.every(({ field, value }) => el[field] === value));    
}

var data = [{
    company: "Acme",
    fiscal_period: '01-2019',
    value: 10
  },
  {
    company: "Acme",
    fiscal_period: '02-2019',
    value: 15
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 8
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 11
  }
]

myFilterFunction = (data, filters) => {    
  return data.filter(el => filters.every(({ field, value }) => el[field] === value));    
}

console.log(myFilterFunction(data, [{field: "company", value: "Acme"}, {field: "value", value: 10}]));

Answer №2

data.filter(item=>{
    for(let key in filterConditions){
        if(item[key]!=filterConditions[key]){
            return false;
        }
    }
    return true;
})

showing an example

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

Add-on or code snippet for Node.js that allows for optional regex groups

Strings in Sequence line 1 = [A B C] line 2 = [A C] line 3 = [B C] Regular Expression /\[?(?<groupA>[A])?(?:[ ]*)?(?<groupB>[B])?(?:[ ]*)?(?<groupC>[C])\]/gm Is there a way to achieve the desired output using a plugin or spe ...

Guide on transforming UTC time from the server to the local time of users during a GET request

I am currently facing a challenge where I need to verify if the date of the last time an element was clicked matches the current date. Due to my server generating the current date which is 5 hours ahead of my local time, there is a discrepancy causing the ...

Combining AngularJS, Google App Engine (GAE), and Endpoints

I've been working on integrating AngularJS with Google App Engine and endpoints. I have a small testing app with a basic API to help me understand how to use Angular with GAE endpoints. A user inputs text and clicks submit to send the entry to the bac ...

What could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

Tips for displaying and sorting two requests within one console

I am currently working on a project to display both folders and subfolders, but only the folders are visible at the moment. function getParserTypes (types, subject) { return types.map((type) => { return { id: type.entry.id, name: type. ...

How can I eliminate the occurrence of "undefined" during the initial iteration of my for loop that iterates over an array?

How can I prevent getting 'undefined' as the last output when using console.log() with a looping construct? let array = ["Fiji", "Santorini", "Bora Bora", "Vancouver"]; let arrayLength = array.length; for(let index = arrayLength; index >= 0; ...

When an href is clicked in an HTML table, I am interested in fetching the value of the first column row

When a user clicks on the "Edit" link in each row, I want to display an alert with the value of the first column in that row. For example, if I click on the "Edit" link in the first row, I should see an alert with the value of the first column in that row. ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Creating an Object with Quoted Key in JavaScript/Typescript for MongoDB's '$push' Feature

Struggling to format the data in order to add an element into a nested array within MongoDB. Currently attempting this in TypeScript: var data = {$push:{"foo.12.bar":{ prop1: prop1, prop2: prop2, // referenced values above this code snippet ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

What is the best way to transfer information from df ~ to my webpage?

I'm currently working on a pie chart that visualizes the disk space usage on my Linux machine. I need help figuring out how to properly parse this data onto a microservice URL. Any assistance would be greatly appreciated. Here's what I have so f ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

The createElement function in Vue.js does not always return a fully formed component

There is a scenario where I need to create a functional component for a specific purpose. The task at hand involves taking all the children elements and adding some additional props to them, but only to those that are custom components of type ChildCompone ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

Looking to automatically scroll to the bottom by clicking on text using javascript/jquery?

I am currently working on a website project where I have a specific requirement. I need the webpage to scroll towards the bottom when a particular text is clicked, using JavaScript/jQuery. <p class="ml-2 mb-2 d-flex view_profile_options"><a hre ...

What is the most efficient method for converting a string into an object in a Node.js environment?

This code seems to be functioning correctly, but it appears quite lengthy. Is there a more concise approach to achieve the same result? The primary objective here is to extract a sorting parameter from an HTTP query and use it to sort a collection in Mong ...

Customizing CSS to differentiate the color of active card headers in a Bootstrap accordion

I currently have a basic bootstrap accordion set up, as shown below. My goal is to style the .card-header element of only the expanded .card section without impacting the other .card-header elements. Is there a way to specifically target the expanded ite ...

Move the object by clicking on it and dragging

I need help figuring out how to move my 3D object in .gltf format to a different position when a checkbox is checked, and then back to its original position when the checkbox is unchecked. I attempted to create a transition function for this purpose, but t ...

Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.&a ...