What is the best way to sort an array within an array based on multiple key values?

const usersLanguageData = {
  transactionId: 6847655349501841000,
  count: 5,
  providerList: [
    {
      code:['US'],
      weekendOfficeHours: false
    },
    {
      code:['US','IND'],
      weekendOfficeHours: true
    },
    {
      code:['US','IND','AUS'],
      weekendOfficeHours: false
    },
    {
      code:[],
      weekendOfficeHours: false
    },
    {
      weekendOfficeHours: true
    }
  ]
};

let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
  return filterKeyName1.every(function(a) {
      console.log(e[a])
      return filterValue1.includes(e[a]);
  });
});

console.log(filteredProviderData);

The above snippet showcases the transformation of usersLanguageData into an object. The goal is to apply filters using a specific key, such as 'code' and values like ['IND','US']. This filtering logic retrieves the 2nd and 3rd objects from the usersLanguageData array. Similarly, there's another filter value (filterValue2), currently commented out, which would fetch the 1st, 2nd, and 3rd objects based on the specified criteria.

Answer №1

It is recommended to utilize the every() method within the function once more. Additionally, ensure to validate the existence of e[a] before executing every() as one of your elements may not contain the key code.

const usersLanguageData = { transactionId: 6847655349501841000, count: 5, providerList: [ { code:['US'], weekendOfficeHours: false }, { code:['US','IND'], weekendOfficeHours: true }, { code:['US','IND','AUS'], weekendOfficeHours: false }, { code:[], weekendOfficeHours: false }, { weekendOfficeHours: true } ] };

let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
  return filterKeyName1.every(function(a) {
      console.log(e[a])
      return e[a] && filterValue1.every(x => e[a].includes(x));
  });
});

console.log(filteredProviderData);

Answer №2

To apply a filter based on a specific value and object property, you can use an empty array.

const languageData = { id: 6847655349501841000, total: 5, dataList: [{ code: ['US'], hours: false }, { code: ['US','IND'], hours: true }, { code: ['US','IND','AUS'], hours: false }, { code: [], hours: false }, { hours: true }] };

let searchKey = "code";
let filterValues = ['IND','US'];
let filteredResult = languageData.dataList
    .filter(object => filterValues.every(value => (object[searchKey] || []).includes(value)));

console.log(filteredResult);

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

Tips for extracting the src attribute from a dynamically generated iframe

My dilemma stems from a function that generates an iframe with content on my website, which unfortunately I cannot control as it is loaded remotely. The function initially creates: <span id="myspan"></span> Once the JavaScript function fu ...

What is the best way to utilize Vue in order to automatically scroll to the newest message whenever a new message is added?

I've been struggling to figure out how to make the window automatically move to the bottom of the blue block whenever I input a new message. I haven't been successful so far. Can anyone help me achieve this feature? Thank you in advance. Check o ...

There is no assigned value in scope for the shorthand property. You must either declare one or provide an initializer

I'm just starting out with TypeScript. Encountering the error 'No value exists in scope for the shorthand property 'firstName'. Either declare one or provide an initializer.' while using Prisma with Next.js to create a new user in ...

Refresh Twitter Bootstrap Tooltip after deactivating/removing

I have a quick question. I am currently dealing with data that is constantly changing and displayed from a selected item in a table. To monitor for overflow, I have implemented the following code: if (event.target.offsetWidth < event.target.scrollW ...

Create a compile-time array that is the result of adding two other compile-time arrays together

Imagine having two constexpr arrays (type[N] or std::array<type, N>) constexpr int X[5] { 9, 8, 7, 6, 5 }; constexpr int Y[5] { 1, 2, 3, 4, 5 }; Would you be able to create a new constexpr array by applying an element-wise operation (or constexpr f ...

Run code once ngResource callback is completed

In my controller, I have a function for creating resources with ngResource app.controller 'CalculationsCtrl', ($scope, Calculation)-> $scope.save = ()-> $scope.busy = true Calculation.create($scope.calculation, (successRes ...

Choose dropdown menus that are pre-filled by JSON may require a manual refresh to show the content

Occasionally, I encounter an issue with a JSON file used to populate select boxes, where the items in the drop down fail to display until the page is refreshed. Despite no errors in the console or log, the loading is seamless on most occasions, leaving me ...

Please upload JSON data into a database using Node.js

As a beginner in learning node.js, I have embarked on my "Hello World!" project. The premise is simple - I am requesting a JSON file from the server via an API and receiving a response that looks like this: { "files": [{ "url": "http://auction ...

Troubleshooting the issue with Devbridge JQuery Autocomplete's functionality when using the service

I'm currently working on integrating the devBridge autocomplete feature, but I'm facing an issue with ajax. It works fine when I manually input a json object without using PHP, but my requirement is to fetch data from a database. PHP CODE: < ...

Evaluating two arrays in C while disregarding the sequence of elements within each array

In my C program, I am looking to compare two arrays while disregarding the order of elements within each array. I had a couple of approaches in mind to tackle this challenge. Both ideas are essentially the same. The first idea involves creating a variable ...

What is the best method for merging 24 columns into a single array column in R?

Looking for a more concise solution, I currently have code that consolidates 24 columns of data into a single column array in a dataframe: # Combines values from multiple columns into one using comma as separator. agg_bluetooth_data$twentyfourhours <- ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

Utilize a boolean value to enable the button and remove the greyed

Can anyone help me with using a password strength check to enable/disable a button in JavaScript? I have a function that checks if a password is strong enough and matching, returning a boolean value. How can I use this value to ungrey a button that is by d ...

Expanding the jquery accordion as the page loads

Upon loading the page, the jQuery accordion should automatically open. Once the page is fully loaded, the accordion should compact itself. jQuery().ready(function(){ jQuery('#portslid').accordion({ collapsible: true, autoheight: false, alwaysO ...

Modifying a CSS property with jQuery

If I have the following HTML, how can I dynamically adjust the width of all "thinger" divs? ... <div class="thinger">...</div> <div class="thinger">...</div> <div class="thinger">...</div> ... One way to do this is usi ...

The Node Sass binding for your current environment, which is Linux 64-bit running Node.js 16.x, could not be located

Issue with Module Error encountered in the ./node_modules/sass-loader/dist/cjs.js file: What are the steps to resolve this issue? ...

Having trouble with the installation of js-bson

While attempting to install bson as a dependency of mongodb on my Windows 7 64bit system, I encountered the following error: npm WARN package.json <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97c0f8f4fff2f9e7fbf6f9f2e5d7a7b9 ...

Vue 3 Option api: Issue with v-model input not propagating from child component to parent element

I am currently working on a new project using Nuxt 3, and I have encountered an issue with a contact form where the input values from a child component are not being received by the parent element. Let's dive into the code breakdown: Parent Component ...