Exploring a collection of objects using a filter and specific keyword

I am looking to implement a search functionality in JavaScript using an array, filter, and keyword. The goal is to search through the array based on the filter and keyword provided, and return a new array of objects similar to the original one.

var data = [
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eebedfbecffdef9f3fff7f2b0fdf1f3">[email protected]</a>",nama:"User A", Level:"Super Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9feaecfaedfddff8f2fef6f3b1fcf0f2">[email protected]</a>",nama:"User B", Level:"Super Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0a0c1a0d1c3f18121e1613511c1012">[email protected]</a>",nama:"User C", Level:"Standart"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f180e2a0d070b030644090507">[email protected]</a>",nama:"User D", Level:"Standart"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cf9ffe9fee9ccebe1ede5e0a2efe3e1">[email protected]</a>",nama:"User E", Level:"Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1b4b2a4b3a781a6aca0a8adefa2aeac">[email protected]</a>",nama:"User F", Level:"Standart"}
];
var filter = "Level";
var keyword = "Standart";

//--------Search

console.log(data);

Answer №1

To filter an array in JavaScript, you can utilize the Array.prototype.filter function. This function takes a callback that determines which elements to keep based on a specified condition. According to the documentation:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The callback function used for filtering takes three arguments as explained in the documentation:

callback

The function is a predicate used to test each element of the array. It should return true to keep the element and false otherwise. The function expects three arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array on which the filter was called.

In the example provided below, we are filtering an array of objects based on the value of a specific property (Level). We are keeping only those objects where the Level property matches the specified keyword ("Standart"). Here is the code snippet:

const data = [
  {email: "example1@example.com", name: "User A", level: "Super Admin"},
  {email: "example2@example.com", name: "User B", level: "Super Admin"},
  {email: "example3@example.com", name: "User C", level: "Standart"},
  {email: "example4@example.com", name: "User D", level: "Standart"},
  {email: "example5@example.com", name: "User E", level: "Admin"},
  {email: "example6@example.com", name: "User F", level: "Standart"}
];
const filterBy = "level";
const keyword = "Standart";

const filteredData = data.filter(obj => obj[filterBy] === keyword);

console.log(filteredData);

You can also use ES6 arrow functions to make the code more concise. The following line achieves the same result as the previous filter operation:

const filteredData = data.filter(obj => obj[filterBy] === keyword);

This simplified syntax improves readability by reducing the amount of code while maintaining the logic of filtering based on a specific property value.

Answer №2

To efficiently sift through an array based on specific criteria, you can utilize the array.prototype.filter() method along with a custom function:

var information = [
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="75869284b4ba9dac858192898dcc8497">[email protected]</a>", name:"John Doe", Status:"Active"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38ac3c0cccaceeee8fccdcecdc88fc6cac8">[email protected]</a>", name:"Jane Smith", Status:"Inactive"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0142090908092907091905084723090d05">[email protected]</a>", name:"Alex Brown", Status:"Active"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="346113107011711511051010171536111c1e">[email protected]</a>", name:"Emily Johnson", Status:"Inactive"}
];
var filterBy = "Status";
var keywordSearch = "Active";

//--------Filtering
var filteredInformation = information.filter(function(item) {
    return item[filterBy] == keywordSearch;
})

console.log(filteredInformation);

Answer №3

To selectively extract elements based on a specific condition, you can make use of the filter() function in the following manner:

> var data = [
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e89d9b8d9a89a88f85898184c68b8785">[email protected]</a>",nama:"User A", Level:"Super Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592c2a3c2b3b193e34383035773a3634">[email protected]</a>",nama:"User B", Level:"Super Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2f293f28391a3d373b333674393537">[email protected]</a>",nama:"User C", Level:"Standart"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82f7f1e7f0e6c2e5efe3ebeeace1edef">[email protected]</a>",nama:"User D", Level:"Standart"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9dcdaccdbcce9cec4c8c0c587cac6c4">[email protected]</a>",nama:"User E", Level:"Admin"},
  {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e2b2d3b2c381e39333f3732703d3133">[email protected]</a>",nama:"User F", Level:"Standart"}
];
> var newData=data.filter(function(x) { return x.Level == 'Standart'})
> console.log(JSON.stringify(newData))
[{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="186d6b7d6a7b587f75797174367b7775">[email protected]</a>","nama":"User C","Level":"Standart"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c2c4d2c5d3f7d0dad6dedb99d4d8da">[email protected]</a>","nama":"User D","Level":"Standart"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aadfd9cfd8cceacdc7cbc3c684c9c5c7">[email protected]</a>","nama":"User F","Level":"Standart"}]

Answer №4

A simple solution to achieve your objective would be to utilize the array filter method.

var data = [{
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b6e687e697a5b7c767a727735787476">[email protected]</a>",
  nama: "User A",
  Level: "Super Admin"
}, {
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0e081e09193b1c161a121755181416">[email protected]</a>",
  nama: "User B",
  Level: "Super Admin"
}, {
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f08583958293b0979d91999cde939f9d">[email protected]</a>",
  nama: "User C",
  Level: "Standart"
}, {
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32474157405672555f535b5e1c515d5f">[email protected]</a>",
  nama: "User D",
  Level: "Standart"
}, {
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c0c6d0c7d0f5d2d8d4dcd99bd6dad8">[email protected]</a>",
  nama: "User E",
  Level: "Admin"
}, {
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e5e3f5e2f6d0f7fdf1f9fcbef3fffd">[email protected]</a>",
  nama: "User F",
  Level: "Standart"
}];
var filter = "Level";
var keyword = "Admin";

var resultArray = data.filter((item) => item[filter] === keyword);
console.log(resultArray);

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

Are iFrames being utilized for third-party applications?

I am looking to create a web application that can be extended by other developers with their own applications. Would using iFrames, similar to how Facebook does it, be the best approach? Is this considered a good practice in web development? Are there a ...

Streamline JSON Hierarchy

I am working with a script that generates JSON results in the following format: [ [ [ "maturity_date", "12/19/2017" ], [ "interest_rate", 0.22 ], [ "interest_earned", 264 ], [ "manage ...

I am encountering an issue where the $scope.modal is returning as undefined when attempting to open an Ionic template modal. What

I am currently developing an Ionic application for the iPad. Within one of my templates, I have implemented a treeview with items. My goal is to open other templates modally when users click on these items. However, I encountered an error stating that $sco ...

Grab the current URL using useRouter in a Next.js app

I am using userouter to obtain the URL of the current page and then utilizing the clipboard to copy it. However, I am encountering an issue where the copied content shows as object object instead of the expected URL. Can someone please help me identify w ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...

Unable to proceed with deployment due to the absence of the 'category' property in the '{}' type

Everything seems to be functioning properly - I can add and remove products, all with the properties I specified in the database. However, my deployment for production is being hindered by some errors that I'm encountering. ERROR in src\app&bsol ...

Tips for displaying an alert after a successful form submission and ensuring user input validation

I created a form with PHP code to send emails, but I'm struggling to add an alert without page refresh upon submission. The alert needs to display in green or red text below the button. Validation for email input is needed, as well as protection again ...

Lacking the knowledge on establishing range for amCharts

I am currently utilizing the amcharts plugin to generate visually appealing charts. While browsing through its features, I came across a few interesting ways to add ranges. However, I noticed that the structure of the code for these charts is different fro ...

including identical item in the array

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <body> <script> var app = angul ...

Having trouble with JavaScript not functioning correctly within the Update Panel?

Does anyone know how to include JavaScript from a remote source inside an update panel? I'm trying to add Facebook and Twitter share buttons to my application. Here is the code snippet: The problem is that this code works fine when the page is initia ...

Is there a difference between innerHTML strings and their corresponding strings in JavaScript?

I am facing an issue with a code snippet that seems to have an unusual error. The following code is a simplified version to demonstrate the strange behavior. <html> <head> <script type = "text/javascript"> window.onload = fun ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...

jQuery Widget - Error: The method cannot be found in [object Object]

I am encountering an error when attempting to call my widget. Uncaught TypeError: Object [object Object] has no method 'koSpreadSheet' The plugin code: (function ($) { //Create spreadsheet app $.widget('koSpreadSheet', { ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

Is it possible to programmatically set focus on a DOM element using JavaScript or jQuery?

My code dynamically loads select boxes based on user selections. I have a specific instruction to select an option, which looks like this: //returns a string of <option>s by ID $('#subtopic_id').load('ajax.php?f=newSubtopic&am ...

Registration process in Node Express application encounters persistent loading when accessed through Postman

I've been working on a signup model for user accounts in Node.js, but when testing it in Postman, I encountered an issue where there was no response or failure. This left me stuck and I received the following error message in my terminal: Unhandled ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...