Search through an array of objects to find specific records in Javascript

I'm working on implementing a search filter for my array of objects. Let's assume I have the following array:

let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}]

If I search for zx, the expected result should be:

[{'name': 'mn zx abc'}, {'name': 'zx mn'}]

However, in the case of the last object {'name': 'mnzx'}, I want to avoid it as the term zx is not at the beginning. I hope this clarifies my issue.

Below is the implemented code snippet:

let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}];

let searchedTerm = 'zx';

let result = arr.filter(data => {
    if (data.name.charAt(0) === searchedTerm.charAt(0)) {
        return true;
    }
});

console.log(result);

Answer №1

Are you looking to identify objects based on the presence of a specific word in their name, rather than just specific characters?

An easy way to do this is by splitting the name field into words and then checking for the search term within that split list. If your words are separated by whitespace, you can use the code "mn zx abc".split(/\s+/) to obtain ["mn", "zx", "abc"]. The regular expression /\s+/ matches one or more whitespace characters, allowing us to split the string accordingly.

To check if the search term exists within the list, you can utilize indexOf.

Below is a complete example:

function findMatches(obj, searchTerm) { return obj.name.split(/\s+/).indexOf(searchTerm) >= 0; }

let items = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}];
let results = items.filter(obj => findMatches(obj, "zx"));

Answer №2

To tackle this scenario, I would utilize a regular expression...

// Given array
let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}]

// Search term provided
let searchedTerm = 'zx';

// Creating a new RegExp object to match the search term with preceding space (case-insensitive)
let searchRE = new RegExp(" " + searchedTerm, "i");

let result = arr.filter(data => {
    // Check if data.name (preceded by an extra space) matches the regex pattern
    return searchRE.test(" " + data.name);
});
console.log(result);

Answer №3

If you want to filter an array using regular expressions and word boundaries, you can achieve that by utilizing the array#filter function to extract all occurrences of names containing the letters "zx".

let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}],
    searchedTerm = 'zx',
    result = arr.filter(({name}) => new RegExp( `\\b${searchedTerm}\\b`, "i").test(name));
console.log(result);

Answer №4

To narrow down the array, utilize RegExp.test() along with the word boundary indicator (\b):

let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}, {'name': 'zxmn'}, {'name': 'abczx mn'}];

const result = arr.filter(obj => /\bzx\b/.test(obj.name));

console.log(result);

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

Dynamic font size that adjusts as you change the window dimensions

Is there a way to adjust the font size in HTML so that when I resize the window, the text size adjusts accordingly? It's like setting a percentage for the text based on the size of the container it is in. Let me provide an example of what I have in m ...

Is nodemon waiting for file changes before restarting due to an app crash?

PS D:\CODE\2077\ONLINESHOP> npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44372c2b3440">[email protected]</a> dev D:\CODE\2077\ONLINESHOP > SET NODE_ENV=DEVEL ...

I'm encountering an endless stream of results in the React useEffect lifecycle

When using react hooks, I encountered an issue where the state doesn't update when I login with another account. Strangely, if I remove the dependency array, it results in errors of memory exceeding due to excessive updates. const [admin, setAdmin ...

Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have. The first array contains the IDs of all the cars, while the second array contains information about the types of cars. Here is the data: var arr = ...

How can I retrieve text instead of HTML using jQuery.get?

I'm facing an issue where I am trying to retrieve data from another site using the code below: jQuery.ajaxSetup({ crossDomain: true, dataType: "jsonp text" }); jQuery.get(url, function(rawContent) { console.log(rawContent); }); However, ...

"Experience the convenience of navigating through two slideshows using the user-friendly Easy Slider

I have implemented the Easy Slider 1.7 from on my website for creating slideshows. Everything works perfectly when there is only one slideshow on the page. However, I need to have two separate slideshows on the website located at different places. When I ...

Enhance an item by introducing additional properties derived from its current key-value pairs

I have a task of converting the following object: myObj = { "pageName": "home", "dataExtract": "data1|data2=value2|data3=value3|data4=value4a,value4b,value4c"} Into this format: myObjMod = { 'pageName': 'home', 'dataExtract&apos ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

Unleashing the Power of v-model in Vue.js: A Comprehensive Guide to Referencing Input

I am a beginner in vue.js and I am currently facing an issue with making a get request from a field that has a v-model="embed.url" after pasting a link. The paste event works fine, but I'm struggling to reference the input with v-model="embed.url" and ...

What would be the best TypeScript target and libs to utilize in a transpiler-free Node.js project?

If I am running a TypeScript Node.js project with the command tsc && node build/index.js (where tsc builds into build/ and index.ts is in the project), what values should be used in lib and target in tsconfig.json to ensure access to the latest TypeScrip ...

Steps to access the most recent eventName (determined by date)

I am working with two arrays var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"]; var eventDetails= [{ "source" : "application" "DateTime": "2016-05-12 11:20:00", "eventName" : "DELIVERED" }, { "source" : "application" "DateTime" ...

Adding dynamically generated HTML elements and binding them to an AngularJS controller is a powerful capability that

As I dive into learning angularJS, I am facing a challenge in determining the best architecture for my project. My single page app is designed in such a way that the URL must always remain unchanged; I do not want users to navigate beyond the root route. T ...

What is the best way to extract user input and pass it to an AJAX request URL?

Recently, I successfully completed an AJAX request using AngularJS. You can check out the code here. Everything was working perfectly until I tried to add a dynamic variable (city) to the link like this: $http.get('http://api.wunderground.com/api/KEY ...

My jQuery function is designed to run one time only

I need help with creating a function that randomly selects and displays a place when prompted. However, when I click the button, the function only runs once. $(".place").hide(); var randomNumber = Math.floor(Math.random()*44); $("#button").click(funct ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

The Canvas drawn using JavaScript is not being resized and painted correctly on Safari mobile and Firefox mobile browsers

I created an HTML page that features a canvas element where I am drawing a roulette using JavaScript After checking the CanIuse website, I learned that canvas functionality is supported in Firefox 68 and Safari 4 to 13 <!DOCTYPE html> <html> ...

Retrieve the count of ng-if directives that match a specific ng-repeat content

Imagine a scenario where HTML code looks like this: <md-grid-tile class="gray" ng-repeat="carto in cartoList" ng-if="search(carto)"> <md-button ng-click="changeSVG(carto.fileName)" aria-label="carto.displayName"> <img ...

Having trouble retrieving json data from PHP page using jQuery $.ajax

Having trouble accessing this JSON data in JavaScript, as when I try to alert it the result comes back as undefined Below is the jQuery code snippet: $.ajax({ type: "POST", url: "frmMktHelpGridd.php", data: { labNo: secondElement ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

Having trouble getting three.js to display a sphere on the screen?

I am new to using THREE.js and I'm having trouble rendering a sphere in the center of my canvas. Can anyone help troubleshoot my code? Here is what I have: <canvas id='canvas' width='960' height='720'></canvas ...