What benefits does using _.filter have over _.forEach when dealing with the task of evaluating a value and then outputting another value

As a newcomer to JavaScript, I rely heavily on eslint and plugins for guidance. My code is written for an environment with lodash 3.9.3 and must be compatible with Chrome 40, utilizing es5.

Here's a snippet of my code:

            _.forEach(star.system().planets, function (world) {
              if (world.starting_planet === true)
                if (world.planet) {
                  world.planet.shuffleLandingZones = true;
                } else world.generator.shuffleLandingZones = true;
            });

eslint-plugin-lodash gives me a warning about using an if statement inside a _.forEach, suggesting I use _.filter or _.some instead. The plugin directs me to its prefer-filter article.

In my opinion, using _.forEach is the appropriate choice here since I need to set up a new value within the existing array. However, after attempting a different approach, I came up with

            var startingPlanets = _.filter(star.system().planets, {
              starting_planet: true,
            });
            _.forEach(startingPlanets, function (planets) {
              if (planets.planet) {
                planets.planet.shuffleLandingZones = true;
              } else planets.generator.shuffleLandingZones = true;
            });

I can't help but wonder if this method is less efficient as it involves iterating over two arrays instead of one. Am I overlooking something? Should I disregard the linter in this scenario? Have I misused _.filter in achieving my objective?

Answer №1

Feel free to disregard the linter warning in this case - using filter is appropriate when the intention is to generate another array, so your code is mostly correct.

Wouldn't iterating through two arrays be less efficient compared to just one?

Not necessarily, since lodash utilizes pipelining for optimization, eliminating the need for a temporary array creation. I suggest writing it like this:

_(star.system().planets).filter({
    starting_planet: true,
}).forEach(function (world) {
    var planet = world.planet || world.generator;
    planet.shuffleLandingZones = true;
});

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

What is the best way to transmit data using a 'GET' request with XMLHttpRequest in JavaScript?

Thank you for taking the time to read this post. I'm looking to send data in a GET request using XMLHttpRequest. function useAjax(url,data){ const xhttp = new XMLHttpRequest(); xhttp.onload = function(e) { const resData = ...

What is the significance of having 8 pending specs in E2E Protractor tests on Firefox?

Each time I execute my tests, the following results are displayed: There were 11 specs tested with 0 failures and there are 8 pending specs. The test execution took 56.861 seconds to complete. [launcher] There are no instances of WebDriver still running ...

Attempting to connect with an Elementor Form submission

I am currently working on a functionality to toggle the visibility of a download button once a user has submitted their email through a standard Elementor form. Despite Elementor offering various actions, I have found that I can only achieve this toggle us ...

Obtaining the current month and year from a Kendo calendar

How can I retrieve the current month from a calendar? I need to be able to display the previous, current, and next month and year as I navigate through the calendar's options. ...

I am encountering an error when trying to fetch a JSON response from a PHP script, even though I am able

Below is the Javascript code I am using to initiate an AJAX call from a PHP file: $(document).ready(function(e) { $(function(){ $.ajax({ type:'GET', dataType: 'jsonp', data: { ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

Creating a responsive touch slider: tips and tricks

I am looking to transform my gallery into a touch slider specifically for mobile devices. To achieve this, I have created two sections - one for desktop and another for mobile. I am utilizing the display property in a media query but my slider is not res ...

Activate the jQuery function multiple times

I am currently working on the menu structure for my website <div class="header"> <ul> <li id="menu__lnk_one"><a href="#">Home</a></li> <li><a href="#">Our Story</a></ ...

What is the best way to attach an event listener to a div so that clicking on it increases the width and height of the div by 20%?

I've started working on it and decided to use the same dimensions (100px by 100px) as a previous question. Right now, I'm sticking with just Javascript, but I might incorporate jQuery down the line. One big issue is that in the line (this.style.w ...

When I use a minified version of AngularJS, the error messages become completely

Upon using angular.js, I encountered the following stack trace: [$injector:unpr] Unknown provider: editorPopupManagerProvider <- editorPopupManager <- libStateManager <- libInjectionManager http://errors.angularjs.org/1.2.2/$injector/unpr?p0=edit ...

The alignment of the Div element is incorrect following a fixed video in bootstrap

When I place a div after the video, the div appears on top of the video instead of after it. Additionally, when I change min-width: 100% to width: 100%, the content appears before the video when I resize the browser. body{ font-family: 'Mina', ...

How can I utilize PageFactory with Selenium WebdriverJS?

I am currently transitioning to writing my tests in TypeScript (using JavaScript is also an option) and struggling with understanding how to implement the PageFactory concept from C#. In C#, I typically create separate classes for each page or form on the ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Horizontal scroll functionality featured in a D3 bar graph

I'm currently working on implementing a bar graph with a selection dropdown that includes 3 values: By Date, By Week, By Month (where 'By Date' is the default option). When retrieving data from the backend for 'ByDate', I have a l ...

What methods can be used to reveal the URL or string hidden by the current "Search" button?

I am a beginner with no coding experience. Please forgive me if my question sounds silly. I am interested in learning how to "discover" the correct string to add to an existing internal-domain-url (even though I am not the admin of that domain) in order t ...

Ensuring my Mongo connection string is accurate for hosting a remote database with authorization

Having difficulty replicating the MongoDB connection in NodeJS using Mongojs. mongo --host dds-xxxx.mongodb.rds.aliyuncs.com:3717 -u root -p password --authenticationDatabase admin Here is my current code snippet: /* MongoDB setup */ // Define parameter ...

Returning the user to the previous page after successfully submitting a web form on the current page in a .NET environment

Is there a simple way on a .net website to navigate a user back to the previous page they were on before submitting a form without needing a complex breadcrumb system? For example, imagine moving from Page1.aspx to Page2.aspx, which contains a form. Upon f ...

Converting string to JSON format by splitting it based on names

I recently manipulated a string containing the values "title:artist" by utilizing the str.split method : res = song.split(":"); The resulting output is as follows: ["Ruby","Kaiser Chiefs"] Now, I am curious about how to include the name in this array f ...

The value could not be retrieved because the input name depends on the array index

To determine the name of the input based on the array index, use the following method: <div id="editAboutSantences<%=i%>" class="edit-container"> <div class="input-container"> <label> content: </label> ...