"Enhance Your Searching Experience with Top-Tier AngularJS

Presented below is a dataset:

persons = [
 {
   "age":20,
   "parameter1":94,
   "name":"Foobarin"
 },
 {
   "age":33,
   "parameter1":49,
   "name":"Johan"
 }
]

I am looking to develop a sophisticated live search functionality that can identify specific patterns. For example, inputting "foo a20 p94" should return the first object. a20 - Search based on an age of 20 p94 - Search for parameter1 value of 94 Additionally, any text without a specified prefix will be compared against the name field.

All values, except for names which are case-insensitive, are integers. I intend to restrict prefixes to predefined options like a, p, and exclude formats like age20. The dataset contains approximately 400 entries.

I have already implemented a basic live search that scans all variables within the objects. However, I'm unsure about the next steps. Any suggestions?

Answer №1

While not completely foolproof, this initial approach is where I would begin. Let me explain it in simple terms.

To start off, create a propertyMatrix, which is basically a map linking "prefixes" to the actual property names found in a person object. The main function searchPersons takes a single string (query) and has two key components:

  • The query string gets separated by spaces into an array of "tokens". Each token consists of a name and value pair within an array with a length of exactly 2. If no predefined prefix is found, the token name defaults to name.

  • A filtering process is then applied to the persons array. We go through each person and check against the tokens array, conducting comparisons. If any comparison fails, we exclude that person from the search results.

var propertyMatrix = {
        'a': 'age',
        'd': 'details'
}, 
searchPersons = function(query){

    var tokens = query.split(/\s+/).map(function(t){
        t = t.toLowerCase();
        var n = t.match(/\d+$/), r;
        if(n && n.length) {
            r = t.substring(0, t.indexOf(n));
            if(r in propertyMatrix)
                return [propertyMatrix[r], parseInt(n, 10)];
        }
        return ['title', t];
    }), 

    result = persons.filter(function(p){
        for(var i=0, l=tokens.length; i<l; i++){
            var tkn = tokens[i][0], val = tokens[i][1];
            if(!(tkn in p)) return false;
            if(tkn === 'name'){
                if(p.title.toLowerCase().indexOf(val)<0) return false;
            } else if(p[tkn] !== val) return false;
        }
        return true;
    });

    return result;

};

fiddle

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

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

AngularJS not displaying loader during AJAX request

While utilizing ajax requests with $http, there seems to be a delay due to the server operation taking longer than expected. I have implemented a loader to display while processing the request, but unfortunately it is not showing up on the page. Even after ...

Deploying a Node.js and Next.js application within a single project

I am working on a NextJS 13 project. Inside the same project, I have a Node project located in a folder named server. When deploying to production, this is how my Dockerfile appears: FROM path-to-node16-runtime:latest COPY node_modules ./node_modules CO ...

trouble with retrieving data into an array using angularjs

I recently started learning angularjs and I am facing a problem. I am trying to fetch a bunch of records from an array, but it's not working as expected. Can someone please review my code and point out where I am going wrong? Here is the code snippet ...

Ways to access the ngModel data in a personalized directive

Hey everyone, I'm facing an issue where I'm trying to get the value of an ngmodel when a button in a custom directive triggers a click event. However, it seems like the value isn't ready in the link function. Is my assumption correct? How ca ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

The Gridsome website deployed on Netlify seems to be experiencing some issues. When clicking on links, the pages are not loading properly despite

After deploying my site on Netlify, I encountered an issue where the URL updates when clicking on links on the landing page, but the content does not show unless the page is refreshed. Interestingly, this issue does not occur on my local development server ...

How come attempting to read a nonexistent document from Firestore results in an uncaught promise?

I've been struggling to read and display data from Firestore, but I keep seeing error messages in the console. Encountered (in promise) a TypeError: Unable to read properties of undefined (reading 'ex') Encountered (in promise) a TypeError ...

Creating a property or method on the instance prior to rendering

During my journey of learning Laravel and Vue.js, I encountered a challenging issue that has proven to be quite perplexing. Despite delving into the depths of Laravel and Vue.js documentation, as well as scouring the internet for solutions, I remain unable ...

Creating variables inside an if statement in the JavaScript language

Is it possible to assign a value to a variable based on a condition like this? if (k<12){ var Case=4; } However, when I try to display this variable in the body of the page, it shows up as undefined. document.write(Case); ...

Creating a button that allows users to quickly navigate back to the top of a webpage

On my website, I have a convenient "back to top" feature that allows users to easily navigate back to the top of the page: If you scroll down the page, you'll see this feature in action. This particular feature is part of the theme I'm using on ...

Warning: React JS encountered errors with propType validation and uncontrolled input handling

I've been encountering challenges with React JS and trying to enhance the todoList after completing a crash course. Despite spending 8 hours troubleshooting, I'm still struggling. Hopefully, seeking assistance here will provide me with a fresh pe ...

Setting character limits when defining string variables in TypeScript

Upon reviewing the documentation, it appears that there is no straightforward method to perform type checking for the minimum and maximum length of a string data type. However, is there a possible way to define a string data type using custom types in ord ...

Chrome not displaying Skeletal Animation in Three.js GLB files

I am attempting to implement basic embedded skeletal animation in a .glb model using Three.js The workaround I found is from a discussion on this forum: I have written the simplest code possible. The animation is being located (can be logged into the con ...

Providing Arguments to a Named Function Using Dependency Injection

I am currently working on an Angular app where I am passing a named function into a controller. The issue arises when I try to inject a provider into that controller for use, as I receive a TypeError: object is not a function in the console. My question i ...

I am interested in incorporating the ability to select and scroll the window without needing to interact with the scroll bar by

Imagine a visitor wanting to highlight all the information on a webpage. They choose to start dragging their cursor towards the bottom of the window. How can we enable the webpage to smoothly scroll down as they do this? ...

What is the method to create a polygon in its entirety by utilizing a for loop within Javascript?

After successfully using the Canvas of HTML to draw a convex polygon, I encountered an issue. In the provided code snippet, t2 represents an array of points with getX() and getY() methods. The drawing function performs as expected until it reaches the seg ...

Access RSS feeds externally without relying on any third-party libraries or server-side processing

Looking to integrate an RSS parser that can parse feeds using jQuery/JavaScript without relying on the Google Feed API or any server-side solutions. The goal is to have auto-updating RSS feeds without overloading the server with multiple requests from user ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Setting the default type of an array in props in Vue 2 is a common need for many developers

My Vue component relies on an array of objects as a prop and I always make use of prop validation, especially for setting default values. In this case, my current setup is: props: { items: Array } However, I would prefer it to resemble something lik ...