Sort through a collection of objects depending on various criteria pulled from a separate array of objects

I am working with an array of objects called c, which looks like this:

c = [
  {
     name: 'abc',
     category: 'cat1',
     profitc: 'profit1',
     costc: 'cost1'
  },
  {
     name: 'xyz',
     category: '',
     profitc: 'profit1',
     costc: ''
  },
  {
     name: 'pqr',
     category: 'cat1',
     profitc: 'profit1',
     costc: ''
  }
]

I need to filter this array based on another array of objects called arr:

arr = [
 {
   type:'profitc'
   value: 'profit1',
 },
 {
   type:'category'
   value: 'cat1',
 }
]

The user selects values from this array using a dropdown with multiple select options. If a user selects profit1 and cat1, the filtered output should look like this:

c = [
  {
     name: 'abc',
     category: 'cat1',
     profitc: 'profit1',
     costc: 'cost1'
  },
  {
     name: 'pqr',
     category: 'cat1',
     profitc: 'profit1',
     costc: ''
  }
]

I attempted to filter the array using the code below, but it returned all objects from the c array. Can you suggest what I might be doing wrong and if there is a way to achieve this using lodash?

let result = c.filter(e => {
  let istruecat = true

  //arr is chosen value from the user.
  arr.forEach(element => {
    istruecat = e[element.type] == element.value;
  })
  return istruecat;
})

Answer №1

-To determine the value of `istruecat`, consider using the `reduce` method instead of only focusing on the last entry in the `arr` array:

let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))

Answer №2

To filter the array, you can iterate through all the key/value pairs provided with the objects in the data.

var data = [{ name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', category: '', profitc: 'profit1', costc: '' }, { name: 'pqr', category: 'cat1', profitc: 'profit1', costc: '' }],
    filters = [{ type: 'profitc', value: 'profit1', }, { type: 'category', value: 'cat1' }],
    result = data.filter(o => filters.every(({ type, value }) => o[type] === value));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Check out this code snippet for reducing the list c using the filter array arr to generate a new list. Keep in mind that the new list is created based on the original content of c.

filteredResult = arr.reduce((accumulator, current) => {
    accumulator = accumulator.filter(item => {
        return item[current.type] === current.value;
    });

    return accumulator;
}, c);

Answer №4

Consider this alternative approach for a clear and concise solution:

function customFilter(arrayToFilter, [firstItem, ...remainingItems]) {
    if (firstItem) {
        const {property, filterValue} = firstItem;
        // Use recursion to filter the array based on the specified property and value
        return customFilter(arrayToFilter, remainingItems)
           .filter(item => item[property] === filterValue);
    } else {
        // No more items to filter
        return arrayToFilter;
    }
}

customFilter(arrayToFilter, filterArray);

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

In search of a screenplay that mirrors a specific scenario

I recently came across this website: One interesting feature is that all the content loads dynamically on the same page. Instead of loading separate pages, it pauses to fetch the content before smoothly scrolling to the correct section. ...

Transforming Preg_match_all Array Result Into a Singular String

Currently, I am attempting to match content using preg_match_all. 1- Utilizing preg_match_all for matching purposes. if(preg_match_all('/\<li class=\"relItem ur\">(.*?)\<\/li>/is',$content,$abtractmatch,PREG ...

Express returning null req.body

Struggling with a school project where I need to execute a POST request to add a new user to a database table using Insomnia. Unfortunately, I keep encountering a null value error specifically related to the username field. Interestingly, when one of the T ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

Having trouble setting up Node.js on a Mac computer

Upon completing the regular installation on Mac, I am unable to find Node in the terminal. Even after defining the PATH with the line: export PATH=/usr/local/bin: $PATH, it still does not locate Node or npm in the terminal. ...

How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloadin ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Is it possible to maintain the data types of each individual piece of data when it's divided into an array in

Can the data type of each field be preserved in Javascript after splitting it using the split method? Input: var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'"; When using the split method, the data type of e ...

The data type for JSON writing is not valid (NSConcreteMutableData)

My attempt to send a JSON request using AFNetworking is resulting in an error indicating that the JSON text did not start with array or object and option to allow fragments not set: NSString *post = [[NSString alloc] initWithFormat: @"{& ...

Tips for deserializing JSON data in NewtonSoft into static classes with nested structures

One scenario involves a nested class with static properties, as demonstrated below: public class X { public class Y { public static string YString = null; } } Consider the following JSON data: { Y { "YString" : "World" } ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

Discovering necessary information by iterating through JSON

Being new to vue js, my goal is to loop through the provided JSON data and check if the required data is present within the file. Here is a snippet of the JSON: [ { "id": "text-5", "widget": "hello", "params": { "0": "section-right", ...

Issues with applying styles to custom components in styled-components

I attempted to customize the inner elements of react-id-swiper using the code below: import Swiper from 'react-id-swiper'; import styled from 'styled-components'; const MySwiper = ({ className, children }) => ( <Swip ...

Tips for sorting items in Wordpress with JavaScript / on click?

I am currently utilizing a method similar to the one outlined in this resource from w3 schools for filtering elements within divs. However, I am facing challenges when attempting to integrate this script into my Aurora Wordpress site due to the removal of ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Utilize promise-style for Sequelize associations instead, please

I am in the process of merging information from 3 tables - Products, Suppliers, and Categories. My goal is to retrieve the row with SupplierID = 13. I recently came across a helpful explanation on How to implement many to many association in sequelize, whi ...

Error receiving by React while updating an array with setState() in TypeScript

I am in search of a way to adjust a property of an item within an array by using the updater returned from setState. The function is passed down as props to the child, who then invokes it with their own index to update their status. const attemptToUpdate ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...