Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this:

var users = [

  {
    first: 'Jon',
    last: 'Snow',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85efeaebc5e2eaf1abe6eae8">[email protected]</a>'
  },

  {
    first: 'Ned',
    last: 'Stark',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c7cccdcadddba0ecccc7d4">[email protected]</a>'
  },

  {
    first: 'tywin',
    last: 'Lannister',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f0fdf3edeac4e3ebf0aae7ebe9">[email protected]</a>'
  },

]

I'm working on a method to filter through the object array:

function findMatch(searchTerm, users) {

  var results = users.filter(function(user) {
    return (user.first === searchTerm || user.last === searchTerm || user.email === searchTerm);
  });

  return results;

}

The issue I'm facing is that my search parameter searchTerm must be an exact match to the values in the array... I need it to be able to search based on a partial match instead. Any suggestions?

Your help is greatly appreciated!

Answer №1

Utilize the String#indexOf method to search for a specific string within an array of objects.

function search(str, users) {

  var results = users.filter(function(el) {
    return (el.first.indexOf(str)>-1 || el.last.indexOf(str)>-1 || el.email.indexOf(str));
  });

  return results;
}

UPDATE 1 : For case insensitive searching, utilize the String#toLowerCase method (Only supported in latest browsers).

function search(str, users) {

  var lStr = str.toLowerCase();
  var results = users.filter(function(el) {
    return (el.first.toLowerCase().indexOf(lStr)>-1 || el.last.toLowerCase().indexOf(lStr)>-1 || el.email.toLowerCase().indexOf(lStr));
  });

  return results;
}

UPDATE 2 : A more simplified version using the Array#some method.

function search(str, users) {
  return  users.filter(function(el) {
    return Object.keys(el).some(function(k){
      return el[k].toLowerCase().indexOf(str.toLowerCase())
    });
  });
}

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

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...

Using space as a separator for thousands when formatting integers

In an attempt to change the appearance of 1000 to resemble 10 000, I found numerous examples online on how to add a separator such as a comma or some StringLocal. However, I am looking for a way to use a space instead. Can anyone advise me on which locale ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

How can I upload a folder with subfolders and keep the structure intact?

I'm working on a form that allows me to upload a folder containing both files and subfolders with more files inside. I managed to upload the folder successfully, but when I check my directory, all the files are in one folder without the subfolders. My ...

Error encountered with Next.js and Square API: The Fetch API cannot load due to the unsupported URL scheme "webpack-internal"

I encountered an issue while attempting to retrieve stock data from the Square API. injectGlobalHook.js:1648 Fetch API cannot load webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js. URL scheme "webpack-internal ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Infinite loop caused by Angular JS routing止

I have set up a Django server with the following configuration: urls.py urlpatterns = [ url('^', IndexView.as_view(), name='index') ] landing/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('^.*&a ...

At what stage of the Angular JS application life cycle is this code being loaded?

I am facing a difficult issue with the timing of Angular JS life cycle in relation to the code snippet below. There seems to be a random occurrence where controllers dependent on this code are loaded before it, leading to errors. Even after multiple atte ...

Checking for the existence of a Vue.js component

In the ready: method of the root instance, I have certain tasks to perform but only if some components are not present (not declared in the HTML). Is there a way to verify the existence of a component? ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

Gradient on multiple faces in Three.js

I'm currently struggling with creating an HSV cylinder using three.js. I am facing difficulties in properly mapping the gradient to the faces of the cylinder. Initially, I attempted to create my object in this manner: https://i.sstatic.net/WboAE.png ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

Enhancing the performance of your code by optimizing it using jQuery when a checkbox is either checked or

Looking for ways to optimize a jquery function that toggles a URL parameter based on checkbox status. Any suggestions on how to streamline this code? $('#mapControl').live('click', function(){ var thisUrl = $(location).attr(' ...

Are there any additional performance costs associated with transmitting JSON objects instead of stringified JSON data through node.js APIs?

When developing node.js APIs, we have the option to send plain JSON objects as parameters (body params). However, I wonder if there is some extra overhead for formatting. What if I stringify the JSON before sending it to the API and then parse it back to i ...

What is the best way to access an Ajax response outside of its function using JQuery?

Just starting out with JQuery and wondering how to utilize the Ajax response ( HTTP GET ) outside of the function in my code snippet below: $.ajax ({ type: "GET", url: "/api", success: success, error: error ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

How to Use JQuery to Display Elements with a Vague Name?

Several PHP-generated divs are structured as follows: <div style="width:215px;height:305px;background-color: rgba(255, 255, 255, 0.5);background-position: 0px 0px;background-repeat: no-repeat;background-size: 215px 305px;display:none;position:fixed;top ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

Is there a way for me to utilize the imported data from one component in the context API using an arrow function?

I am trying to utilize placeInfo, reviews, detailsInfo, news from a data file. Instead of using value='hello', I am unsure if I can directly use it like this: value={placeInfo, reviews, detailsInfo, news}, as it is producing an error. Should I st ...

When making a Post Request, the Req.body is found to be empty

Here is the code snippet from various files: In App.js file: app.use(express.json({limit:"30mb",extended:true})); app.use(express.urlencoded({extended:true})); In route.js file: router.route("/register").post(registerUser) Importin ...