implementation of object-array filtering based on a specific order from another object-array

Here is the data I am working with:

arrayA = [{"studentID":1,"Type":"A"},{"studentID":2,"Type":"B"},{"studentID":3,"Type":"C"},{"studentID":4,"Type":"A"}]
filteredArrayOrderlyOn = [{"studentID":1},{"Type":"A"}] (depends on user-selected filters)

Desired Output for arrayA: 
arrayA = [{"studentID":1,"Type":"A"}]

If the filteredArrayOrderlyOn changes based on user input:

filteredArrayOrderlyOn = [{"Type":"B"},{"studentID":1"}] results in no output []
Or if  
fillteredArrayOrderlyOn  = [{"Type":"A"}] 
then output should be:
arrayA = [{"studentID":1,"Type":"A"},{"studentID":4,"Type":"A"}]

I want to filter ArrayA in a specific order, starting with studentID=1 and then Type=A according to the filteredArrayOrderly selection.

I have tried various methods but have not been successful.


newArray = arrayA.filter(function (item) {
    return Object.keys(elem) === Object.keys(item);
  });
})

Additionally, I have attempted using lodash:

 newArray = _.filter(arrayA, function (elem) {
  //     return elem.Type=== filteredArrayOrderlyOn.Type ||  elem.studentID=== filteredArrayOrderlyOn.studentID
  //   });

Unfortunately, I am encountering too many repetitions. Thank you for your help!

Answer №1

To ensure that multiple keys are matched in the filters, you can utilize the Array#every() method:

let arrayA = [
  { "studentID": 1, "Type": "A" },
  { "studentID": 2, "Type": "B" },
  { "studentID": 3, "Type": "C" },
  { "studentID": 4, "Type": "A" }
];

let filteredArrayOrderlyOn = [
  { "studentID": 1 },
  { "Type": "A" }
];

const result = arrayA.filter(item => 
  filteredArrayOrderlyOn.every(filter => Object.keys(filter).every(key => item[key] === filter[key]))
);

console.log(result);

Answer №2

Utilizing lodash allows you to consolidate an array of filters into a single object (filteredArrayOrderlyOn), which can then be used to filter an array of values (arrayA) using _.matches():

const { merge, matches } = _;

const customFilter = (arr, filters) => arr.filter(matches(merge({}, ...filters)));

const arrayA = [
  { "studentID": 1, "Type": "A" },
  { "studentID": 2, "Type": "B" },
  { "studentID": 3, "Type": "C" },
  { "studentID": 4, "Type": "A" }
];

console.log(customFilter(arrayA, [{ "studentID": 1 }, { "Type": "A" }]));

console.log(customFilter(arrayA, [{ "Type": "A" }]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></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

Locating the final index of a given array

What is the method to access the final element of an array in C#? ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

What is the best way to merge these two ng-class expressions?

<ul> <li ng-repeat="(k, v) in chartTags track by k" class="blue-tag"> <div class="tag" ng-class="{blue1: k == 0 , blue2: k == 1 , blue3: k == 2, 'positive': v.direction == 'pos ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Calculating the total number of instances falling within a specified range on Google Sheets

My task is to calculate the number of employee work days falling within specific ranges: `< 30 = 30 and < 90 = 90 and <180`. When trying to determine the count of employees who worked for more than 30 days but less than 90 days, I experimented ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

Error in Controller Due to Unassigned Variable ($scope Problem)

Can anyone explain why $scope.gotData is not accessible outside of the getData.success() call in the following AngularJS code? Although I can see the value of scope.gotData displayed in my view using {{gotData}} in my index.html, I'm unable to use $sc ...

A unique technique for creating a stunning visual effect with images using

Can anyone help me with this issue: Check out this animated GIF The images in my project are overlapping when scrolling! How can I achieve a similar effect for my images? Is there a tutorial or plugin available for this? Here is the current code sn ...

Issues with using this.transitionTo in Ember.js

Exploring the integration of Ember.js with Phonegap, I have implemented the Confirm API. However, I am encountering an issue where executing this.transitionTo('index') from the event-driven function onConfirm is proving to be a challenge. Any th ...

Unable to access API due to CORS Policy issues in a Node.js application

I encountered a CORS policy error while attempting to link my React web application to my Node.js server due to different endpoints. To address this issue, I attempted to utilize CORS, a Node.js package that provides a Connect/Express middleware for enabl ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...

React's reset button fails to clear user inputs

Within my App, I have a straightforward form. I recently discovered that using a button with the attribute type="reset" should clear all input fields, but for some reason it's not working properly in React. Is there something crucial I am ov ...

Create a bootstrap navbar that remains fixed at the top of the page while scrolling

Looking to create a navigation bar similar to this one: I have implemented the stickUp jQuery script for my navbar, but it is not working as expected. I am unsure how to resolve this issue. Here is the link to the jsfiddle: http://jsfiddle.net/52VtD/792/ ...

Tips on sorting a struct array with qsort

Tasked with the challenge of retrieving a binary file, reading it into an array comprised of structs and sorting it based on a specific array within each struct has proven to be quite the hurdle. At this moment in time, my main struggle lies within the rea ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: https://i.sstatic.net/iy0ZV.png https://i.sstatic.net/trfrL.png Here is my ...

add the AJAX response to the specified div element

I'm currently using an ajax call to retrieve movie data from the IMDb API for 'The Shawshank Redemption'. My goal is to display this data within the designated div element. <div id="movie-data"></div> Here's my current Jav ...

I am attempting to set a string value to an array comprised of arrays of characters

Currently, I am facing an issue where when I try to assign a string value (char *) to an element in an array of char arrays, the last read value is placed into every element instead of the specific one I intended. The code snippet causing this problem is l ...

Utilizing parentIds to construct a hierarchical array structure in PHP

I am currently facing a challenge in setting up a multi-level list structure with the use of parentId to establish parent-child relationships. Initially, the top-level items have a parentId set as NULL. Here is an illustration of some sample entries: < ...