Is it possible to utilize filter in place of forEach in Javascript?

Is there a way to refactor the function below that currently uses forEach to instead use filter? I've searched online but couldn't find a suitable solution.

pendingPaymentsUtils.getPendingPayment = paymentId => {
  const payments = pendingPaymentsUtils.getPendingPayments()
  let payment = {}

  payments.forEach(function(_payment) {
    if (_payment.id === paymentId) {
      payment = _payment
      return false
    }
  })

  return payment
}

I attempted the following approach, but it didn't work as intended.

pendingPaymentsUtils.getPendingPayment = paymentId => {
  const payments = pendingPaymentsUtils.getPendingPayments()
  let payment = {}

  payments.filter(function(_payment) {
      payment = _payment
      return _payment.id === paymentId ? false: true
  })

  return payment
}

Answer №1

  1. filter function provides an array of results, so simply return that and eliminate the payment variable.
  2. The statement
    _payment.id === paymentId ? false: true
    can be shortened to just
    return _payment.id === paymentId;
  3. Utilize implicit returns with arrow functions to make this even more concise.
  4. It appears that using find might be more suitable than filter.

Consider the following approach:

pendingPaymentsUtils.getPendingPayment = paymentId => {
  const payments = pendingPaymentsUtils.getPendingPayments();
  return payments.find(payment => payment.id === paymentId);
}

You can further shorten it by removing the unnecessary payments variable:

pendingPaymentsUtils.getPendingPayment = paymentId =>
  pendingPaymentsUtils.getPendingPayments().find(payment => payment.id === paymentId);

Edit:

If no object is found, return an empty object instead of undefined:

pendingPaymentsUtils.getPendingPayment = paymentId =>
  pendingPaymentsUtils.getPendingPayments().find(payment => payment.id === paymentId) || {};

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

Ensure that text is aligned alongside an image only when both elements are enclosed within <p> tags

When using an API to pull markdown content from Contentful and converting it to HTML with ReactMarkdown, a common issue arises. The resulting HTML structure often places the text content in separate paragraphs such as: <p>Some text content</p> ...

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

A step-by-step guide on integrating Validate.js into your Vue.js project

As a novice full stack developer, I am embarking on the journey of building a portal for my work. The server side will be developed in asp.net mvc 5, while the client side (HTML, CSS, SASS, JS) has been developed by another company. My task is to handle se ...

What is a method to retrieve the value of an associative array using the value found in a different array?

$gender = array ('boy', 'girl', 'trangender'); $shopping_data = array( 'boy' => array( 'accessory' => array('belt','wallet','watch'), ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

iOS displaying CSS Transform issue exclusively

Creating a website that is fully mobile responsive is my goal. However, after designing the header, I realized that it wasn't displaying correctly on IOS devices like my iPad. The "Transform: translateX(-100%);" statement was functional on Android pho ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

Python Class Antics

I'm a beginner at Python scripting and I'm having trouble with my code. I have created two types of objects, rooms, and items, and trying to add an item to a room's inventory, but it's not working. Can someone please help me figure out ...

nodejs callbacks and their return values

Hey guys, I'm having trouble resolving an issue with a JavaScript callback return. Here's the function in question: //Function to get user's contact list function get_contact_list(data) { //Retrieve user ID based on ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Issue with running the Jquery each function within a textbox inside an ASP.NET gridview

Below is the gridview markup: <asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle" AutoGenerateColumns="False" Width="100%" EmptyDataText=& ...

managing associative array keys with special characters in php

Here is an example of my object. I am trying to access the object using an array, but I am unable to do so because there is a special character (@) as a prefix. Can anyone provide guidance on how to access the array in this scenario? SimpleXMLElement Ob ...

Transferring components as props from a higher order component (HOC) to the wrapped component

In my recent React project, I incorporated Higher Order Components (HOCs) to pass components as props to the wrapped component. I am curious if this approach has any drawbacks. Below is an example: HOC: import AnotherComponent from './a' funct ...

Guide on incorporating interactive visuals or features within a panoramic image viewer through the use of THree.js and webGL

Seeking advice on how to incorporate more images and hyperlinks within a panoramic viewer, similar to the examples below: This particular link Panorado js viewer. I have noticed that these viewers feature embedded hyperlinks and overlays, I have attempt ...

Experience the power of Vue.js combined with Axios for easy data fetching and manipulation with JSON

Apologies for the repeated posting, but I have exhausted all solutions found online to no avail. This issue seems to be quite common, yet I am unable to resolve it. After dedicating an entire day to solving it, I am throwing in the towel. It must be a mino ...

What is a method for saving a file from Chrome to a network drive using scripting language, even though it's currently functioning in IE?

In a SharePoint 2013 document library, I have implemented a JavaScript function that captures user access to files. The function creates a .txt file containing information about the user ID, username, and file path, which is then saved to a network drive l ...

What is the correct method for retrieving values from a JSON array?

To extract information from a JSON file, I have created a function as shown below: function getarray(){ $http.get('http://localhost/prebuilt/countries.json') .success(function(data) { $scope.countries = data; }); return data; } Howe ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...