Sorting through a collection of objects using various criteria in typeScript

Hello team, I have an array of objects that looks like this:

data = [
  { name: "Pork", category: "Food", subcategory: "Meat" },
  { name: "Pepper", category: "Food", subcategory: "Vegetables" },
  { name: "Beef", category: "Food", subcategory: "Meat" },
  { name: "banana", category: "Food", subcategory: "Fruit" }
];

My goal is to filter the data array based on specific conditions.

{
   "filters":[
      {
         "filters":[
            {
               "field":"subcategory",
               "operator":"eq",
               "value":"Vegetables"
            }
         ],
         "logic":"or"
      },
      {
         "filters":[
            {
               "field":"name",
               "operator":"eq",
               "value":"Pepper"
            },
            {
               "field":"name",
               "operator":"eq",
               "value":"banana"
            }
         ],
         "logic":"or"
      }
   ],"logic":"and"
}

One way to achieve this is by using process() in Kendo like so:

kendo.data.Query.process(data, {
  filter: {
    logic: "and",
    filters: [{
      field: "subcategory",
      value: "Meat",
      operator: "eq"
    }],logic:"or"
  }
});

Are there any alternative methods to filter data without relying on process()?

Answer №1

This method utilizes a filters object that includes an array and a logical component to specify conditions.

The array may consist of other objects with the filters logic as well as an object defining the constraints for a single property, which must match an item in the provided data array.

At present, only one operator is supported.

const
    operators = { eq: (a, b) => a === b },
    quantifiers = { and: 'every', or: 'some' },
    filter = ({ filters, logic }) => item => filters[quantifiers[logic]](f => 'filters' in f
        ? filter(f)(item)
        : operators[f.operator](item[f.field], f.value)
    ),
    filters = { filters: [{ filters: [{ field: "subcategory", operator: "eq", value: "Vegetables" }], logic: "or" }, { filters: [{ field: "name", operator: "eq", value: "Pepper" }, { field: "name", operator: "eq", value: "banana" }], logic: "or" }], logic: "and" },
    data = [{ name: "Pork", category: "Food", subcategory: "Meat" }, { name: "Pepper", category: "Food", subcategory: "Vegetables" }, { name: "Beef", category: "Food", subcategory: "Meat" }, { name: "banana", category: "Food", subcategory: "Fruit" }],
    result = data.filter(filter(filters));

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

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

When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this: { "id": "some type of user id", "name": "The name of the user", "permiss ...

Async function captures error being thrown

I am looking to implement an async function in place of returning a promise. However, I've run into an issue with rejecting using error throwing: async function asyncOperation() { throw new Error("Terminate this application."); } (async () => { ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

What are some techniques for creating a volumetric appearance with THREE.Mesh in WebVR?

Currently, I am in the process of transferring an existing three.js project to WebVR with Oculus Rift compatibility. This application takes an STL file as input, generates a THREE.Mesh based on it, and displays it in a virtual scene. While I was able to su ...

javascript loop exhibiting unpredictable behavior when making ajax requests

window.addEventListener('load',function(){ var last=0; var sub=document.getElementById("sub"); var msg=document.getElementById('msg'); var msg_bx=document.getElementById("msg_bx"); var re=new XMLHttpRequest(); re.open("GET","handler ...

The use of numbers for identification

Currently, I am in the process of extracting data from a JSON array that has the structure as shown below "title": Title, "chapters": { "13c": { "words": 123, "spaces": 321 }, "15d": { "w ...

Executing a JavaScript function from the form attribute value in HTML: Steps to follow

<html> <head> <script type="text/javascript"> function add() { num1 = 20; num2 = 30; total = num1 + num2; return total; } </script> & ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

Tips on how to resize, position, and scale an object effectively using three.js

Recently delving into the world of three.js, I decided to experiment with importing models using the gltf loader. Upon loading a specific 3D model, my scene transformed to showcase a mesmerizing view, as depicted https://i.sstatic.net/l4jNy.png. However, ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

Scattering a 3D array in MPI to form tetragonal prisms

Greetings to all! I am currently working on scattering a 3D array in a tetragonal prism format. To help you visualize, check out the image below: Imagine the large cube as a 3D array (let's say with dimensions of 4x4x4) and processors P0..P3 assigned ...

What is the best approach to passing multiple variables to a JavaScript function in HTML/PHP?

Seeking help with calling a javascript function from PHP through embedded HTML code. Below is the script: <script> // THE FOLLOWING JAVASCRIPT FUNCTION REDIRECTS TO EDITUSER.PHP AND PASSES USERID VALUE. function startMaint(mo, yr){ ...

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

What is the method for incorporating text into the Forge Viewer using three.js?

Currently, I am attempting to incorporate TextGeometry into the viewer using Three.js. I am curious about the feasibility of this task and the steps to achieve it. After exploring the documentation, I encountered challenges as the Forge viewer operates on ...

Choosing a populated control using JavaScript results in an empty value

Within my ASP.NET applications, I incorporate a server-side HTML select control. <select id="CompanyDropDown" runat="server" style="width:330px"> </select> To populate and pre-select items in this control, I use a JavaScript function triggere ...

"Vue is failing to actively update an input that relies on changes from another

I am working on a project where the selected country automatically determines the phone country code. I have set it up so that when I change the country, the corresponding country code should update as well. https://i.sstatic.net/861tq.png Within a custo ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

Running out of memory while working with a C# string array

My goal was to merge the content of two text files by combining each line from file1 with every line from file2. For example: file1: a b file2: c d result: a c a d b c b d This is the code I used: { //int counter = 0; string[] lines1 ...

Issue with Angular variable not updating in the view, despite being successfully updated in the logs

This has been one of the most frustrating issues I've ever encountered. Snippet from my html file: <!--test_management.html--> <div ng-controller="TestCtrl as tcl"> <ul class="nav nav-tabs"> <li class="active"> ...

What is the best way to display the first 50 names from an array?

I am dealing with an array that contains over 100 names, but I only need to display the first 50 names from the array. While researching this issue, I came across a topic discussing how to retrieve the first x elements of an NSArray in Cocoa. Here is the ...