Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties.

if ($scope.filters.filter1)
    $scope.filteredEntries = $scope.filteredEntries.filter(function (o)
    {
       return o.field1 === $scope.filters.filter1
    });

if ($scope.filters.filter2)
    $scope.filteredEntries = $scope.filteredEntries.filter(function (o)
    {
       return o.field2 === $scope.filters.filter2
    });

However, this code repetition is not ideal. I am looking for a way to encapsulate the selection logic into a separate function, but since the conditions for selecting are different in each case, I am unsure how to proceed. Can I somehow pass the condition as a parameter or implement it differently? Any suggestions on how to achieve this would be appreciated.

In my approach, I envision creating something like the following pseudo code:

expression = e => e.field == value;
miniFilter(expression);
...
function miniFilter(expression)
{
   $scope.filteredEntries = $scope.filteredEntries.filter(function (expression)
   {
      return expression;
   });
 }

I hope my objective is clear. My understanding of JavaScript's methodology is limited, so please bear with me. Thank you.

Answer №1

Here is the solution to the initial repetitive code:

var data = [
  {field1: 'Tom', field2: 30}, 
  {field1: 'Max', field2: 30}, 
  {field1: 'Max', field2: 30}
];
var $scope = { filters: {
    filter1: 'Max',
    filter2: 30
  }
};

function MiniFilter(input, filters) {
  for (var prop in filters) {
    var filVal = filters[prop];
    if (filVal)
      input = input.filter(function(item) {        
        return item['field' + prop.match(/\d+$/)[0]] == filVal;
      });
  }
  return input;
}

var result = MiniFilter(data, $scope.filters);
console.log(JSON.stringify(result))

Solution using "expressions":

var data = [
  {field1: 'Tom', field2: 30}, 
  {field1: 'Max', field2: 30}, 
  {field1: 'Max', field2: 30}
];
var $scope = {filters: [
  function(x){ return x.field1 == 'Max';},
  function(x){ return x.field2 == 30;}
]};

function MiniFilter(input, expressions){
  for(var exp of expressions)
    input = input.filter(exp);
  return input
}

var result = MiniFilter(data, $scope.filters);
console.log(JSON.stringify(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

Creating dynamic columns in tables using AngularJS by clicking on ng-repeat items

The backend is providing me with this type of response. [ { "id": "1", "name": "Roshan", "av": "1000", "compname": [ { "id": "43", "cname": "TCS", "constraint_value": "", "details": [ { ...

Clojure users may wonder how to retrieve the value of a text field upon clicking a button generated with Hiccup

Within my Hiccup Clojure program, I have a requirement to extract the value of a text field whenever a user clicks on a button. Subsequently, this extracted date needs to be added to a URL. Initially, I tried utilizing "ng-model" from AngularJS for this pu ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

Steps for building a Bootstrap grid of thumbnails

I need to display an unknown number of thumbs. Below is a sample of the HTML rendered: <div class="row-fluid"> <ul class="thumbnails"> <li class="span3"> <a href="#" class="thumbnail"> &l ...

I could use some help understanding how to identify the parent file so I can elevate a state

I'm facing a challenge in lifting up a state so that I can utilize it across various pages. The confusion lies in determining where to reference the states, given the uncertainty regarding the parent location. Since this is my first attempt at designi ...

"Encountering a 400 Error While Attempting to Edit Requests in NodeJS/A

Currently, I am building an application using Ionic/Angular with a NodeJS backend. Within this project, I have created an update form that allows users to modify or delete a specific row. While the deletion function is working fine, I am facing some challe ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Utilizing Material UI's TextField components for validating React forms

I've spent the past hour researching this topic and unfortunately, there isn't much information available on the internet. My goal is to validate input fields to ensure that all fields are filled out; otherwise, an error will be displayed. The le ...

Converting an array of numbers into an object using JSON

When I use jQuery to encode an array, this is the JSON I receive: {"1":{"name":"11233","po":"121212","po_item_number":"000001","po_item_material_code":"material","po_item_description":"assemble","sales_order":"11000000","sales_order_item":"10","tracable": ...

Reactjs is currently not integrated with Firebase

I recently completed a project in reactjs and realized it requires authentication. My initial thought was to connect it with Firebase as it seemed like the most straightforward option. Following a tutorial on YouTube, however, I encountered some difficult ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

Error: Custom Service is behaving unpredictably

My latest project involves creating a customized service. While the service function is returning data as expected, I encounter an issue when calling it in the controller - it returns 'undefined'. Service: var toDoListServices = angular.module( ...

Remove information using Axios in ReactJS by interacting with an API

I have successfully pulled data from the jsonplaceholder API and stored it in my state. However, I am struggling with implementing the deleteContact() method to remove the data. Can anyone provide guidance on how to properly execute the deleteContact() met ...

Limiting the Size of Highcharts Maps with maxWidth or maxHeight

My attempt to adjust the maxWidth of my world map using highcharts isn't altering its size. I have experimented with the following: responsive: { rules: [{ condition: { maxWidth: 500 }, ... As recomme ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

Manipulating all components of a specific type in App.vue with VueJS: Is it possible?

Consider this template with FruitPrices as a component: <template> <div id="app"> <div> <span @click=SOME_FUNCTION> Change currency </span> <FruitPrices fruit="apple"></FruitPrice ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

The attribute "property" is not found in the specified type of "Request<ParamsDictionary>"

Struggling to enhance the Request interface in the express package with custom properties, I keep encountering this TypeScript error: TS2339: Property '' does not exist on type 'Request<ParamsDictionary>'. Any ideas on how to re ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...