Tips for sorting an array based on various criteria from a separate array

Seeking assistance with filtering results from the data array using two arrays.

var data = [{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},{"role":"Fullstack", "languages": ["JavaScript"]}]
var selectItem = ["CSS"];

Objects are added to selectItem[] after selection from a UI in data.

The goal is to output by filtering from the data array against selectItem.

The challenge lies in filtering based on values from both role and languages in selectItem.

For example:

var selectItem = ["Frontend","CSS"];

An attempt has been made to filter out the result:

  var users = this.myJson.filter(
        (el) =>
          this.selectItem.includes(el.role) ||
          el.languages.some((e1) => this.selectItem.indexOf(e1) >= 0)
      );
      console.log(users);

How can the data array be filtered with multiple keys, considering both languages and role?

Update:

The current query works but struggles when new items are added to selectItem, like:

 var selectItem = ["Frontend","CSS", "HTML"]; 

It returns all values as it contains CSS. Looking to filter only if CSS, HTML, and Frontend are present in data.

var data = [
{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},
{"role":"Fullstack", "languages": ["JavaScript"]},
{"role":"Frontend", "languages": ["CSS","JavaScript"]}

]

var selectItem = ["Frontend","CSS", "HTML"];

var users=data.filter(el => selectItem.length &&
   (selectItem.includes(el.role) ||
    el.languages.some(e1 => selectItem.includes(e1)) )
);
console.log(users);

Expected output:

[{
  languages: ["HTML", "CSS", "JavaScript"],
  role: "Frontend"
}]

Looking for the best approach to filter with multiple keys from an array object.

Answer №1

After reviewing your initial attempt, it seems that you are specifically seeking elements that meet all of the keyword criteria rather than just some. To adjust to this requirement, I have revised my response:

var data = [
{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},
{"role":"Fullstack", "languages": ["JavaScript"]},
{"role":"Frontend", "languages": ["CSS","JavaScript"]}];

var sel = ["Frontend","CSS","HTML"];

var users=data.filter(el => {
  if (sel&&sel.length){
//  let elall=[el.role].concat(el.languages);
    let elall=[el.role,...el.languages]; // <-- Aakash Bashyal <3
    return sel.every(se=>elall.includes(se))
  }
});
console.log(users);

In my updated code snippet, I've introduced a temporary local array called elall that holds all of the keywords present in an element from both the role and languages attributes. This way, the .every() method applied to sel verifies whether each keyword in

sel</code is included within the <code>elall
array.

Answer №2

By using the following code snippet, you can achieve the expected outcome:

data.filter(element => 
    selectedItems.includes(item => item == element.role) || 
    selectedItems.some(item => element.languages.find(language => language == item))
);

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

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

React Native app experiences a start-up crash caused by SoLoader problem

I'm encountering a problem with my Android app (iOS is working fine). Every time I build it, the application closes before launching. I've tried various solutions found on Github and here, but haven't been able to resolve it yet. The instal ...

Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error referenceError: items is not defined. Can anyone help me figure out why this error is occurring or provide some guidance? Upon initial inspection of the code, it seems like the issue may be rel ...

Combine the PHP table with the Javascript table

I am facing a challenge where I have a table in PHP and another table in Javascript. My goal is to combine the elements of the PHP table with the elements of the Javascript table. I attempted to achieve this using the push method: <?php $tabPHP=[&apos ...

Performance issues with jquery addClass and removeClass functions observed in Internet Explorer 11

I am currently working on an application that monitors nodes within a cluster, and I have created a visual state example to demonstrate this. Each small box in the grid represents a node, and when hovering over a node, the rest of the nodes in that particu ...

Implementing the ui-tinymce Directive Within a Different Directive

I am attempting to implement the ui-tinymce directive within another directive: angular.module("risevision.widget.common.font-setting", ["ui.tinymce"]) .directive("fontSetting", ["$templateCache", function ($templateCache) { return { restrict: ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

Validation of AngularJS dropdown selection must be completed before submitting the form

I have a Dropdown list within my form and I want to disable the submit button until an element is selected from the list. Here is my button: <input type="submit" value="Get" ng-disabled="form.$invalid " /> I attempted to implement the solution foun ...

When using the checkbox array in Node.js, only the last checked value is returned instead of the entire array

I'm in the process of extracting the checked values from checkboxes through req.body. When I check only one, there are no issues and I receive an object with the value in req.body. However, when I check more than one, it only returns the last checked ...

React Module cannot be found: Error: Unable to locate - import paths

New to coding and currently working on a website using React. Encountering three errors persistently: ERROR in ./src/Components/Pages1/Home.js 6:0-50 Module not found: Error: Can't resolve './Components/Cards/Cards1.js' in 'C:\Use ...

How can states be passed down as props in React?

This might be a beginner question, but I've been struggling with it all day. Any help would be appreciated. Apologies for the length, I just wanted to explain everything I'm having trouble with I am attempting to create custom buttons by build ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

React: Premature exit, Fewer hooks executed than anticipated

I'm currently working on a chrome extension project where I'm trying to update an object based on a change in the current tab. However, I keep encountering an error that says I've rendered fewer hooks than expected. How can I resolve this is ...

Embark on a journey through Express.js routes with a unique context

After grappling with this issue for a few days, my brain feels fried and I can't seem to find the most efficient solution. My ultimate goal is to be able to repeat a route journey with new context data at the start. For example: app.get('/test& ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

Discovering shared elements across several arrays in PHP

Is there a way to find the common elements among four different arrays in PHP? I need to compare multiple arrays and identify the elements that they all share. [0] => Array ( [0] => 121186 [1] => MPE129 ...

Uploading files in ASP.NET MVC without creating a view, utilizing Valums Ajax Uploader technology

I recently completed a tutorial on ASP.NET MVC file uploads using Valums plugin and made sure to place all the necessary js, css, and gif files in their respective folders. However, I am facing an issue where the view is not displaying anything. <link ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...