Filtering an array of objects by multiple arrays of keys

My data set consists of an array of objects

const Data = [
  {first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer'},
  {first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'engineer'},
  {first_name: 'Cindy', city_name: 'Tokyo', age: 32, designation: 'influencer'},
  {first_name: 'Barn', city_name: 'sydney', age: 34, designation: 'lawyer'},
  {first_name: 'Yolanda', city_name: 'Seoul', age: 32, designation: 'chef'},
  {first_name: 'Mike', city_name: 'London', age: 42, designation: 'bartender'},
  {first_name: 'Olivia', city_name: 'LA', age: 34, designation: 'officer'}
]

In addition to the data array, I have an object containing filters

const Filters = {
  first_name: ['Ammy', 'Dave', 'Mike'],
  city_name: ['LA'],
  age: [22, 34]
}

The task at hand is to filter the data using all specified conditions (and condition). For the given Data and Filters, only the row with Ammy should be displayed. The complexity arises from the fact that the filters can apply to a single key or multiple keys. It could be just { first_name: ['Dave']}

Previous attempts in writing filtering code did not consider applying all filters

const newData = []; 
Object.entries(Filters).map(([filter, Values]) => {
  const filteredData = Data.filter(item => {
    if (Values.find( value => value === item[filter])) {
      newData.push(item); 
    } 
  });  
}) 

Answer №1

To achieve the desired outcome, simply filtering the data array rather than mapping the Object.entries() of filters is necessary.

You can accomplish this by iterating through each object in the data array (e.g. person) and verifying if every key from filters corresponds to a value present in that particular person object by utilizing the .some() method. If this condition is met, then returning true will retain the object in the final array:

const data = [{ first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer' }, { first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'engineer' }, { first_name: 'Cindy', city_name: 'Tokyo', age: 32, designation: 'influencer' }, { first_name: 'Barn', city_name: 'sydney', age: 34, designation: 'lawyer' }, { first_name: 'Yolanda', city_name: 'Seoul', age: 32, designation: 'chef' }, { first_name: 'Mike', city_name: 'London', age: 42, designation: 'bartender' }, { first_name: 'Olivia', city_name: 'LA', age: 34, designation: 'officer' } ];
const filters = { first_name: ['Ammy', 'Dave', 'Mike'], city_name: ['LA'], age: [22, 34] };

const filterEntires = Object.entries(filters);
const res = data.filter(person => filterEntires.every(
  ([key, values]) => values.some(val => val === person[key])
));
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

Steps to create a hover effect similar to that of a website (increasing grid size on hover)

Looking to create a hover effect for my boxes similar to the one on this website: I've examined the code of the website above and searched extensively for a similar feature without any luck. Could anyone offer assistance with this, please? ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

When navigating to a new route using history.push in React, it's important to ensure that the correct state is

My goal is to implement a smooth exiting animation with framer motion based on the user's current route and next destination. I specifically want the background to slide away only when transitioning from route A to route D. To achieve this, I decided ...

Ways to verify if a Discord.js snowflake is present in a collection of other identification numbers

I'm currently developing a Discord.js bot and I want to create a system where only specific IDs listed in a JSON file can trigger certain commands. However, I'm unsure about how to implement this logic within an if statement. if (message.author. ...

Is it acceptable to halt the execution of an async route handler in an Express application using a return statement?

My async route handler is set up like this: router.post('/', async function (req, res, next) { try { const { username, email, password } = req.body const { errors, userData } = validateRegistrationInput(username, email, password) if ...

Focus is lost on React input after typing the initial character

Whenever I input text, the focus is lost. All my other components are working fine except this one. Any ideas why this might be happening? I attempted to create separate components and render them in my switch statement, but it still doesn't work. O ...

What are some strategies for troubleshooting asynchronous errors in JavaScript function calls?

I'm currently working on an asynchronous JavaScript code that utilizes the async method findDevices from the class Devices, which is located in a separate file. This method involves performing a mongo find operation within the IDevices collection. Her ...

Using Vue.js to dynamically update values in JavaScript code or tags

I've encountered an issue that I'm having trouble articulating, but I'll do my best to explain. Upon loading the page, the following code snippet, which uses jinja-based placeholders, is executed: <div class="ui container"> ...

What is the best way to transform individual associative arrays into a single, organized indexed array?

print_r($element_attrs); displays various arrays extracted from an xml file with weather summaries: Array ( [WEATHER-SUMMARY] => Increasing Clouds ) Array ( [WEATHER-SUMMARY] => Thunderstorms ) Array ( [WEATHER-SUMMARY] => Thunderstorms Likely ...

I am unable to retrieve images using the querySelector method

Trying to target all images using JavaScript, here is the code: HTML : <div class="container"> <img src="Coca.jpg" class="imgg"> <img src="Water.jpg" class="imgg"> <img src="Tree.jpg" class="imgg"> <img src="Alien.jpg" class=" ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Breaking down a Python array into individual characters for an Excel spreadsheet

After inputting the code into Excel, I noticed that every character is spaced out. This leads to "Tuesday" appearing as "T,u,e,s,d,a,y" in Excel. My objective is to have each cell in Excel display a complete word rather than individual characters. With n ...

Ways to verify if one div in jQuery contains identical text to another div

I need help with a jQuery script to remove duplicate text in div elements Here's the requirement: If div1 contains the text "hi" and div2 also contains "hi", then div2 should be removed Below is my current code snippet: <script src="https:/ ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

Generate a library using Vue CLI from a component and then import it into your project

When using vue-cli to build my lib, I run the following command: "build": "vue-cli-service build --target lib --name myLib ./src/component.vue" After the build, how can I import my component from the dist folder? Importing from path-to-myLib/src/compone ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

What is the best way to capture dynamic import errors in JavaScript?

I am currently developing a website using Next.js. My goal is to utilize dynamic import import() to load a module dynamically, even if it may not exist. If the module does not exist, I am fine with suppressing it: const Blog = async () => { let L ...

Exploring ways to loop through objects in a React application

I'm trying to figure out how to modify the code below to iterate through a custom object I have created. function itemContent(number) { return ( <div > <div className="item"> <div className="itemPic& ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Store the Ajax JQuery selector within an array for safekeeping

I am completely new to working with Ajax and would appreciate some assistance in storing data from an Ajax request into an array. I have browsed through various solutions on this forum, but so far, I have been unable to resolve my issue. The Ajax respons ...