What are some ways to provide the find() method in JavaScript with a specific search argument?

I've been exploring ways to search within an array while iterating through it. One method I stumbled upon is the find() method.

Take a look at this example:

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

Now, I want to find a specific fruit dynamically, but I'm struggling with implementing it. Basically, I'm aiming for something like this:

function findCherries(fruit, fruitName) { 
    return fruit.name === fruitName;
};

inventory.find(findCherries('cherries'))
//"true is not a function"

Is there a way to pass an argument to the find() method in order to search based on that parameter? If not, what alternative method could I use to search for objects within an array dynamically?

Answer №1

Utilizing a closure (where your function is required to return another function) in the following way:

function searchForFruitByName(name) {
    return function(fruit) {
        return fruit.name === name;
    }
}

inventory.find(searchForFruitByName('cherries'))
// {name: "cherries", quantity: 5}

Answer №2

Here's a solution to try:

// function to find one fruit by name in inventory
function findFruitByName(name, inventory) {
  return inventory.find(function(item) {
    return item.name === name;
  });
}

// function to find all fruits with a certain name in inventory
function findFruitsByName(name, inventory) {
  return inventory.filter(function(item) {
    return item.name === name;
  });
}


let inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5},
  {name: 'cherries', quantity: 88}
];

console.log('One', findFruitByName('cherries', inventory));
console.log('All', findFruitsByName('cherries', inventory));

Answer №3

Although closures are typically used, another option is to provide the thisArg parameter to the Array.prototype.find method like this:

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findFruit(fruit) {
    return fruit.name == this;
};

console.log(inventory.find(findFruit, 'cherries'));

This approach may not be the best choice, as it can be a) less clear and b) because this is an Object, it needs to be converted into a primitive string through non-strict equality == or by explicitly converting it to String(this). However, it can still be useful in certain situations as mentioned here.

Answer №4

Can I specify an argument for find() to locate a match based on that argument?

Absolutely. The first snippet of code you provided already achieves this: the specified argument is a function designed to search for cherries.

The argument supplied to .find() must be a function capable of performing the comparison you desire. This function can be created anonymously right where it's needed:

let result = inventory.find(function(item) {
  return item.name === "cherries";
});

You can also utilize an arrow function to condense the code significantly:

let result = inventory.find(item => item.name === "cherries");

If the value you seek is stored in another variable:

let fruit = "cherries";
let result = inventory.find(item => item.name === fruit);
// OR
let result = inventory.find(function(item) {
  return item.name === fruit;
});

(It's worth noting that arrow functions are not supported by IE, but then again, neither is the `.find()` method...)

Answer №5

To utilize the thisArg parameter of the find method as an argument, you can refer to the example below (although I have used filter, you are free to use find instead)

var customFind = function(element) {
  return (element.indexOf(this) !== -1); // checks if 'element' string contains a substring provided by 'this'
};

console.log(["abc", "123", "xya", "xyz"]
            .filter(customFind, "a"));         // input: "a"
//output: ["abc", "xya"]

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

Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns? For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests. ...

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

For each error that occurs when there is only one item in the array during a post request

My nodejs server has a JSON schema like this: var UserSchema = new Schema({ nick: String, deviceId: String, visivel: Boolean, checks: [{date: {type:String},log: {type:Number},lng: {type:Number}}] }); In the Post code ...

An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation: function loadHistory() { var detailsForGe ...

Update the CAPTCHA, while also refreshing the entire registration form

JavaScript Snippet <script language="javascript" type="text/javascript"> function updateCaptcha() { $("#captchaimage").attr('src','new_captcha_image.php'); } </script> New Image Code <img src="new_ ...

Step-by-step guide for activating a text box when a check box is marked

I'm looking to activate and deactivate two text boxes when a check box is selected. Currently, only one text box is enabled when the check box is checked. How can I modify my code to enable and disable two text boxes based on the check box status? Her ...

Creating a PHP JSON response that incorporates an HTML layout is a dynamic

I'm having some trouble with a certain issue: I am attempting to develop a jQuery/AJAX/PHP live search bar. Although I am successfully calling search.php, the response displayed in the console always includes the contents of my master.php file (which ...

Is there a way to determine the actual time or percentage completion of a file upload using Telerik RadUpload?

Utilizing the Telerik upload file control with manager is a key component of my project: <telerik:RadUpload ID="RadUpload" Runat="server" MaxFileInputsCount="5" /> <telerik:RadProgressManager ID="RadProgressManager" Runat="server" /> For clie ...

Add the element of surprise. The element must be either a Model, an Association, or an object

Struggling with configuring PostgreSQL with Node.js, I followed this tutorial and encountered an error without any specific details: Here is the stacktrace Unhandled rejection Error: Include unexpected. Element has to be either a Model, an Association or ...

Determine whether AngularJS directive method binding automatically defaults to angular.noop

In my directive, I am passing a function to a plugin which will use it with a specified value. Let's simplify things by ignoring data changes: angular.module('some.directives', []) .directive('myDirective', [, function () { ...

Steps for choosing the nth HTML row with jQuery

I'm facing a situation where I need to be able to select the nth row of an HTML table based solely on the id of the selected row. You can see exactly what I mean by checking out this JSFiddle Demo <table class="mytable1"> <tr><td i ...

The data in AngularJS is not being successfully incorporated into the service

Utilizing angularjs and ajax, I am attempting to retrieve data from a webservice and pass it to the controller. To accomplish this, I am using a holder (a factory method or service). The setup works fine without the webservice, but when trying to fetch dat ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

deleting a aircraft upon the addition of another in three.js

I am striving to implement a button that toggles between different terrain-generating functions and removes the previous terrain. The current issue I am facing is that the planes stack on top of each other. You can see an image of the problem here. There ...

Activating/Deactivating Checkbox using Jquery

I'm having trouble getting this code to function properly when there are multiple instances of datepicker on the page. When selecting the option "I currently work here," it is affecting all groups instead of just the current one, which is not the des ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

Utilizing Zoomdata data in conjunction with echarts index.js to create a dynamic stacked line chart

I am currently working on integrating Zoomdata with an echarts javascript chart to visualize data from 20 different computers in a stacked line chart format. While I can manually code this setup, I am looking for a way to dynamically link the data from Zoo ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...