Filtering by element of an array in Angular.js

I have a collection of json objects, for instance:

 $scope.users = [
    {name:'Maria',age:25,skills["Angular.js","Node.js"]},
    {name:'Maxime',age:28,skills["HTML","MongoDB"]},
    {name:'Noemie',age:28,skills["CSS","MongoDB"]}
 ]

I am looking to create a search feature. Users should be able to input one or multiple keywords and then my application will filter the variable accordingly.

For example, if a user inputs "28" and "MongoDB", I will store these queries in an array like this:

$scope.queries = [28,"MongoDB"]

I will then filter my users array based on these queries.

It is important to mention that $scope.users is not as straightforward as the example provided; it contains nested arrays and other complex structures. Therefore, I would prefer a function that can effectively search for keywords.

I need guidance on how to implement such a function or filter.

Answer №1

Although not the most efficient solution, you may give this a try

let filterCriteria = [28,"MongoDB"];
let filteredUsers = $scope.users.filter(function(user){
  let isMatch = false;
  filterCriteria.forEach(function(criteria){
    if ( user.name == criteria || user.age == criteria || user.skills.indexOf( criteria ) != -1 ) 
    {
       isMatch = true; //assuming you want any of the criteria to be found rather than all
    }
  });
  return isMatch;
});

DEMO

 
let users = [
    {name:'Maria',age:25,skills : ["Angular.js","Node.js"]},
    {name:'Maxime',age:28,skills : ["HTML","MongoDB"]},
    {name:'Noemie',age:28,skills : ["CSS","MongoDB"]}
];

let filterCriteria = [28,"MongoDB"];
let filteredUsers = users.filter(function(user){
  let isMatch = false;
  filterCriteria.forEach(function(criteria){
    if ( user.name == criteria || user.age == criteria || user.skills.indexOf( criteria ) !== -1 ) 
    {
       isMatch = true; //assuming you want any of the criteria to be found rather than all
    }
  });
  return isMatch;
});

document.body.innerHTML += JSON.stringify(filteredUsers, null, 4)

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

Encountering a problem where a 'List<dynamic>' type is not recognized as a subtype of a 'Map<String, dynamic>' type

I am currently working on a flutter app that is meant to showcase users in a list format. While I have been successful in fetching and printing the data, displaying it presents an issue for me as I keep encountering this error message Exception has occurre ...

The array error is looking for a specific class

I'm struggling to understand why this code is not working and it's showing a .class error. Any assistance would be highly appreciated. Thank you! public static int displayPercentageAndGrade(int assignMax, int assignScoreArray, int labMax, int la ...

JavaScript server variable

How can I access a server-side asp.net variable in JavaScript? I'm trying to achieve something like this: function setBookmark(val) { document.getElementById('<%# hBookmark.ClientID %>').value=val; } Is there any way to accomplis ...

What does Martin Fowler imply when he advises against automatic deserialization in a REST API implementation?

In his article about enterprise REST, Martin Fowler advised against relying on automatic deserialization in APIs: My preference is to steer clear of automatic deserialization entirely. This approach usually leads to the same issues as WSDL, where consum ...

Combining two multi-dimensional arrays while updating any duplicate values

I attempted to utilize "array_merge($a,$b)" but it doesn't suit my needs. Here are the details of two arrays : $a = Array ( [Mike] => Array ( [100] => Array ( [quantity] => 1 ...

Using jQuery slider and sortable in combination

I have been experimenting with combining jQuery slider and jQuery sortable on the same HTML page. Check out this jsfiddle solution by ostapische Initially, the slider (which highlights items in the list) works perfectly when the page is first loaded. Howe ...

Should the .js file type be omitted in the <script> tag for semantic accuracy?

Upon reviewing some inherited code, I noticed that JavaScript files are being linked in the following format: <script src="/js/scriptfile" type="text/javascript"></script> However, I was expecting to see: <script src="/js/scriptfile.js" ...

Transform a linear JSON structure into a hierarchical tree structure, resembling a JSON object

while($row = mysqli_fetch_assoc($result)) { echo (json_encode($row)); } The JSON output from the echo: {"name":"REPORTING","parent":"null","children":"BO"}{"name":"IHS","parent":"BO","children":"1"}{"name":"TOMCA ...

Rendering nested JSON using React Native

After successfully loading a JSON object and storing it in this.state, I am encountering difficulty accessing nested levels beyond the initial level. Here is an example of the JSON file being used: { "timestamp": 1530703572, "trend": { "value": 0, ...

What could be the reason for event.stopPropagation() not functioning properly with a switch statement

Could you please explain why the function event.stopPropagation() is not working on the switch element? Whenever I click on the switch, it prints the console log for the switch. However, when I click on the surrounding area (row), it logs the row event in ...

Is there a way to integrate my fixed elements with the API call seamlessly?

As a newcomer to web development, I've encountered a hurdle in my current project. I'm working on fetching API images and attempting to attach links to them in my code. However, this process would increase the number of arrays, which poses a chal ...

Is there a way to show all the items within a specific folder simply by clicking on the folder's name?

When a folder name is clicked, I would like to display all images from that particular folder. Currently, the code displays the list of folder structure and images separately, but my goal is to show the images only when the folder name is clicked. List of ...

Basic AngularJS framework with minimal external dependencies

I have been searching for an AngularJS skeleton to set up my project, but it seems like all the skeletons I find online require the installation of numerous dependencies through npm and/or bower. Due to security concerns at the firm where I am working on ...

Making the transformation of an array into an object is made easier by utilizing the Array.map() and Array.reduce() methods in JavaScript

When I receive data from an API call, it is in the following format: const testScheduleData = [ { DATE: "2021-06-20", SELECTED: false, STARTINGDAY: true, ENDINGDAY: true, STATUS: "WORK", ...

The execution of the enzyme wrapper.update() function results in the removal of the value prop from the ref input

Take a look at this Code Sandbox that showcases a test scenario related to the issue being discussed. The test in the mentioned Code Sandbox is failing as outlined in the question: https://codesandbox.io/s/react-jest-and-enzyme-testing-c7vng The goal here ...

Issues arise when attempting to use JavaScript to update the innerHTML content of a webpage

I have created a JavaScript code (shown below): function gup(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex ...

Problem with Handlebars: When compiling, TypeError occurs because inverse is not recognized as a function

I've hit a roadblock with an error that I just can't seem to solve. My goal is to dynamically compile a template extracted from a div on the page, provide it with content, and then display it in a designated area of my webpage. Here's the s ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Incorrect comparison of floats within arrays resulted in inaccurate results

I am currently working on a project that involves comparing values in an Array which are dynamically fetched from a website, and I'm using Selenium-IDE to assist with this comparison. However, I've noticed that the values are being compared as s ...