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

Variations in speed with closely related jQuery expressions in Internet Explorer

When running in Internet Explorer, test the performance of executing an expression like: $('div.gallery div.product a"); against a similar expression: $('div.gallery').find("div.product").find("a"); It has been found that sometimes the s ...

.htaccess rules for rewriting URLs in AngularJS using html5mode and ui-router

Although this question has been asked numerous times on Stack Overflow, I am still unable to achieve the desired results. I have attempted to use this link: htaccess redirect for Angular routes You can find more information at: https://github.com/angular ...

Tips for stopping a click from going through a fixed element to the one in the background

My website features a fixed positioned header with a search box, overlaying content below it (thanks to the higher z-index). When I click on the search box, an event handler is triggered. However, the click response also passes through the header to the ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

Utilizing component data in Vue.js to configure the router-link attribute

Is there a way to pass component data in <router-link to="...">? Here's an example: var data = { files: [{ name: "test", path: "/test" }] }; var component = { data: function() { return data; ...

I am encountering difficulties with importing Node modules into my Vue.js project

Having some trouble importing a node module via NPM in a Vue.js single file component. No matter which module I try to install, it always throws an error saying These dependencies were not found. I'm following the installation instructions correctly ( ...

Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data: { "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

On Linux systems, Node.js in JavaScript interprets strings as objects only

I'm encountering an issue with my Discord.io bot. I am attempting to run it on a Linux server, but the Linux version of Node.js keeps treating the contents of a string as a separate object, leading to the following TypeError: TypeError: Object IT&apo ...

Invoke another component to display within a React.js application

Click here to view the code snippet. I am facing an issue with my React components. I have component A that handles fetching and rendering a list, and I also have component B that accepts user input. How can I trigger component A from component B? It seem ...

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Sending an array from one page to another with Vue

I'm facing the challenge of passing an array from one page to another. When accessing the next page on form submission using this.$router.push('path'), is there a way for me to also transfer the array so that it can be accessed on the new p ...

What is the best way to maintain an active listGroup even after reloading the page?

I'm currently working on a gallery project using the #listGroup bootstrap component. I would like to ensure that when a user clicks on one of the albums, the active state of the #listGroup persists even after the page is reloaded or refreshed. How can ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

CodeIgniter Flexi Auth - Redirect users promptly upon login expiration

Is it possible to use the CodeIgniter Flexi Auth library to redirect a user to the login page immediately upon session expiration, displaying a message stating: "Your login has expired, please login again," rather than waiting until page load? I'm co ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

The jQuery slider does not have the functionality to be dragged

My Ruby on Rails app is utilizing a jQuery slider, but I am encountering an issue where I am unable to drag the slider button. However, it does move successfully if I click anywhere inside the slider. Here is the code snippet: <div id="slider">< ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...