Exploring an array of objects by comparing the values within an object's array

I possess an item with two fields filter1 and filter2 containing values in the form of arrays

let filter = {filter1:["mine","your"]: filter2:["C","D"]}
//values are not predetermined

The data is structured as an array of objects

let data = [
{ id:1, filter1:["mine"], filter2:["E","C"]},
{ id:2, filter1:["mine"], filter2:["E","C","F"]},
{ id:3, filter1:["your"], filter2:["C"]},
{ id:3, filter1:["your"], filter2:["D","C"]},
{ id:5, filter1:["other"], filter2:["F"]},
...
]

I need to sift through the objects that have either of the fields present in a specific key. For example, if filter is

{filter1:["mine"]: filter2:["F","D"]}
, it will first look for any element of filter1 in the filter1 of the data object, and then search for any element of filter2 which is also found in the filter2 of the data object. It will return the object if any of them is discovered.

A few examples

Result for

{filter1:["mine"]: filter2:["F","D"]}

result = [
{ id:1, filter1:["mine"], filter2:["E","C"]}, //since filter1 "mine"
{ id:2, filter1:["mine"], filter2:["E","C","F"]}, //since filter1 "mine"
{ id:3, filter1:["your"], filter2:["D","C"]}, //since "F" and "D" from filter2, "D" is present
{ id:5, filter1:["other"], filter2:["F"]}, //since "F" from filter2 is found
]

Result for

{filter1:["your"]: filter2:["F","G"]}

result = [
{ id:2, filter1:["mine"], filter2:["E","C","F"]}, //since "F" from filter2 is present
{ id:3, filter1:["your"], filter2:["D","C"]}, //since filter1 is "your"
{ id:5, filter1:["other"], filter2:["F"]}, //since "F" from filter2 is present
]

Result for {filter1:[]: filter2:["D"]}

result = [
{ id:3, filter1:["your"], filter2:["D","C"]}, //since filter2 has "D"
]

Answer №1

You can achieve the desired outcome by utilizing a blend of .filter(), .some(), and .includes():

const data = [
  { id:1, filter1:["mine"], filter2:["E","C"]},
  { id:2, filter1:["mine"], filter2:["E","C","F"]},
  { id:3, filter1:["your"], filter2:["C"]},
  { id:3, filter1:["your"], filter2:["D","C"]},
  { id:5, filter1:["other"], filter2:["F"]}
];

const search = ({ filter1, filter2 }) =>
  data.filter(item =>
    item.filter1.some(fItem => filter1.includes(fItem)) ||
    item.filter2.some(fItem => filter2.includes(fItem))
);

const result = search({ filter1:["mine"], filter2:["F","D"] });
console.log(result);

Answer №2

To enhance the method suggested by RoMilton, you can utilize some() on the Object.entries() of the provided filter object. This approach involves iterating through each key and filter_array using nested some() calls.

If you incorporate the currently processed data element property into an array using Array#concat(), you can accommodate non-array properties in the filter object, such as the id.

const data = [
  { id: 1, filter1: ["mine"], filter2: ["E", "C"] },
  { id: 2, filter1: ["mine"], filter2: ["E", "C", "F"] },
  { id: 3, filter1: ["your"], filter2: ["C"] },
  { id: 3, filter1: ["your"], filter2: ["D", "C"] },
  { id: 5, filter1: ["other"], filter2: ["F"] }
];

const search = (array, filter_object) =>
  array.filter(item =>
    Object.entries(filter_object).some(([key, filter_array]) =>
      [].concat(item[key]).some(fitem => filter_array.includes(fitem)))
  );

const filter = { filter1: ["mine"], filter2: ["F", "D"] };
const result = search(data, filter);

console.log(...result.map(({ id }) => ({ id })));

const filter2 = { id: [5], filter1: ["mine"] }
const result2 = search(data, filter2);

console.log(...result2.map(({ id }) => ({ id })));
.as-console-wrapper { max-height: 100% !important; top: 0; }

The usage of concat() can also be implemented in a fixed solution to handle properties that might not be arrays within your data set.

const data = [
  { id: 1, filter1: "mine", filter2: ["E", "C"] },
  { id: 2, filter1: ["mine"], filter2: ["E", "C", "F"] },
  { id: 3, filter1: ["your"], filter2: ["C"] },
  { id: 3, filter1: ["your"], filter2: ["D", "C"] },
  { id: 5, filter1: ["other"], filter2: ["F"] }
];

const search = ({ filter1, filter2 }) => (
  data.filter(item =>
    [].concat(item.filter1).some(fItem => filter1.includes(fItem)) ||
    [].concat(item.filter2).some(fItem => filter2.includes(fItem))
  ));

const result = search({ filter1: ["mine"], filter2: ["F", "D"] });
console.log(result);

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 PHP, implement a function to insert a delimiter into a string retrieved from a

Merchant Id|Merchant|Website|Transaction In Period|Voids In Period|Gross Sales Amount|Total Commision in Period 9766|Mountains Plus Outdoor Gear|www.MPGear.com|1|0|88.91|8.89 12447|Meritline.com|www.meritline.com|5|0|52.86|3.71 16213|East Coas ...

Conceal the item and reveal it upon clicking

There are three div boxes included in a rotator script. However, when clicking on the right button, all three boxes appear overlapping each other instead of showing one at a time. How can I make it so that only one box is shown and the others appear upon c ...

Generating buttons by iterating over a list

I had asked this question previously and received some responses, but things got a bit messy so I decided to post it again here. Here is where I am setting up the scroll view: ScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,480)]; Scroll ...

Animate the width of a div element with CSS from the center

I'm working on a cool menu animation as a little experiment. Here's what I've got so far: HTML <div class="menu"> <div class="bar"></div> <div class="bar"></div> <div class="bar"></div> < ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...

Merge the properties of two class instances deeply

What is the best method for deep merging two instances of ES6 classes similar to lodash? The end result should be an instance of the same class with a deep merge of both instances' properties. ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

Show a confirmation dialog box using bootbox that includes a link when the user selects OK

I am currently experimenting with integrating bootbox.js into a test page. However, I am facing an issue where the href tag in the hyperlink triggers regardless of whether the user selects the Cancel or OK button on the bootbox. Is there a way to include ...

Filter in AngularJS to display a different value retrieved from the database depending on the current iteration value

I am in the process of migrating an existing Laravel (and jQuery) application to Angular/Laravel. Here is a snippet from my code: <td>{{ Person::byId($record->id) }}</td> During my iteration, I called a function to retrieve a name based o ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

Google charts do not allow data columns on axis #0 to be string type

I am utilizing PHP to populate a Google area chart from data stored in a phpMyAdmin database. The information consists of two columns: Date and Price. Below is the code I have implemented: <script type="text/javascript"> google.charts.load( ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

What is the best way to organize a numerical string array in Swift?

In my current project, I am attempting to organize an array that is linked with three other arrays. The main array consists of a combination of strings and numbers, such as ["Day 1","Day 2","Day 3",...]. The additional three arrays contain strings. At the ...

On my webpage, there are two buttons labeled "Save" and "Complete". I am in need of creating two distinct alerts for each of the input fields

If the user does not enter a value in the input box for charge_amt, I have set up an onbeforeunload jQuery event to notify them. Once they enter the amount, they will be able to save. <td><input type="hidden" name="charge_cc" value="0" class=""&g ...

I am in need of eliminating repetitive comments from each post

data structure can you help figure out what is causing the issue in this code that seems to be removing old comments? mutations:{ getPosts(state) { let unique = [...new Set(state.posts)]; for (let i = 0; i < uniq ...

Detecting page change cancellation using jQuery/Javascript event

Is there a way to detect when a user cancels a page load in an AJAX-based website with heavy modal/loading screen usage? We rely on modal/loading screens to indicate important actions, but for full page changes that can take a couple seconds, we want to i ...

Steps to initiate an iframe event using Jquery

Is there a way to trigger an event within an iframe from the parent document? Here's a hypothetical scenario of what I am attempting to achieve: <iframe id="i"> <div id="test"></div> <script> $(document).ready(function( ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

How can I clear the value of "token-field" data in jQuery after successfully submitting a form?

I've attempted to reset the value: <input type="text" class="token-field" name="meta_keyword" id="meta_keyword" value=""> $('#meta_keyword').val(); However, it doesn't seem to be functioning as expected. ...

Exploring directory organization in GraphQL Queries using GatsbyJS

In my portfolio, I have organized my work into categories, pieces, and pictures in a cascading order similar to a child-parent relationship. The folder structure reflects this hierarchy, with the main problem being explained in more detail below. Folder s ...