sorting an array using key and value criteria

How can I use Underscore.js to filter an array based on a specific key and value? Currently, my code searches for all fields' values, but I only want to search based on the key and value. Can you provide guidance on how to achieve this using Underscore.js?

I would appreciate any help or suggestions. Thank you.


 var sortedArray = _.sortBy(_.filter(arr, function (obj) {
                      return _.values(obj).some(function (el) {
                          return (typeof el ==="string" && el.match(new RegExp(searchStr, "i")));
                       });
                      }), function (obj){
                            return obj[colName];
                    });
}
{
  "recordsTotal": 5,
  "recordsFiltered": 5,
  "aaData": [
  {
    "firstname": "Pradeep",
    "lastname": "Kumar",
    "city": "Bangalore",
    "country": "India"
  },
  {
    "firstname": "John",
    "lastname": "Wells",
    "city": "Calcutta",
    "country": "India"
  },
  {
    "firstname": "Praveen",
    "lastname": "Garg",
    "city": "columbo",
    "country": "Srilanka"
  },
  {
    "firstname": "Joe",
    "lastname": "Wells",
    "city": "Luton",
    "country": "UK"
  },
  {
    "firstname": "Rita",
    "lastname": "Wahlin",
    "city": "houston",
    "country": "USA"
   }
 ] 
}

Answer №1

Apologies if my question was not clear. I have managed to find a solution using the code snippet below.

    function searchColumnData(array, searchString, columnName){
       var filteredArray = _.filter(array, function (object) {
                       return (_.property(columnName)(object).toString().match(new RegExp(searchString, "i")));
                      });

    return filteredArray;

}

I hope this explanation proves helpful to someone.

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

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

Building a personalized payment experience using Python Flask and Stripe Checkout

I'm attempting to set up a customized checkout integration with Stripe on my Flask web application and I've encountered some issues. After copying the code from the Stripe documentation (located at https://stripe.com/docs/checkout#integration-cu ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Placing an image on a three.js cube using overlay does not function properly

I attempted to superimpose an image onto a cube by utilizing code from GPT chat and Blackbox AI, but in both cases, I encountered a black screen. I saved the code in a file named test.html and tested it on Google Chrome and Opera GX browsers, only to be me ...

In MongoDB, we can unravel numerous arrays within embedded documents and display each array as an individual document in the output

Take a look at the code snippet below. The scenario field is an embedded document with arrays, and I aim to display each array as a single document in the output. Each array contains embedded documents, so extracting fields from those would be useful. I wo ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Routing static pages in Angular 2

I successfully created a static page using Angular 2. When I run ng serve and visit my page, it functions as intended. Specifically, I can navigate to a specific page by typing in the URL, such as www.mysite.com/resume. However, after uploading it to my si ...

Is it possible to pass a JavaScript array to a local variable by reference?

Within my namespace, I have an array defined in JavaScript like this: app.collection.box = []; Additionally, there is a function within the same namespace structured as follows: app.init = function () { var box = this.collection.box; // ... code ...

Exploring Enum properties within an angular js select drop down

I am working with an enum in Java that looks like this: public enum myEnum{ enum1("enumDisplayVal1"), enum2("enumDisplayVal2") myEnum(String displayValue) { this.displayValue = displayValue;} private String displayValue; public String getDisp ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

Is it possible for a cloud function to safely carry out asynchronous tasks after it has fulfilled its promise?

Is it safe for a cloud function to execute async tasks after returning its promise? Take into consideration the following code pattern: exports.deleteUser = functions.auth.user().onDelete(async (user) => { const uid = user.uid; asyncTask1(uid); ...

Encoding in JSON format for utilization in Google Maps

I'm currently struggling with formatting data into JSON for Google Maps integration. Specifically, I need it to be structured like this: {"title":"Park Ave Penthouse", "location": {"lat": 40.7713024, "lng": -73.9632393}}, {"title":"Chelsea", "loc ...

How to create a custom hover effect for IconButtons in Material-UI

Customizing Hover Effects on IconButton I am currently using an IconButton component from Material-UI and have noticed a subtle grey border that appears when hovering over the icon. I am looking for a way to disable this hover effect, as I cannot seem to ...

Attempting to incorporate the jquery-mousewheel plugin into the jquery cycle2 library

I've been working on integrating the jquery-mousewheel plugin (https://github.com/jquery/jquery-mousewheel) with the jquery cycle2 plugin. Initially, everything was running smoothly until I encountered an issue where mouse scrolling was generating ex ...

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

Integrate AngularJS service with Angular framework

Attempting to utilize the $log service within an angular 2 app, it seems that the following steps are necessary: Set up a module that includes the service you wish to inject. Utilize UpgradeAdapter's upgradeNg1Provider method. Therefore, I proceede ...

A pop-up window for selecting a file within an <a> tag

Is there a way to create an Open File dialog box on a link within my webpage? I attempted <input name="uploadedfile" type="file"> However, it only functions as a button and does not allow for the selection of multiple files. I would like somethin ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...