Mastering the use of lodash's differenceBy function with a custom iteratee: Identifying array elements with

I am looking to create my own custom iteratee function for lodash differenceBy that will return an array of values greater than 5.

As per the documentation, the iteratee is used to "generate the criterion by which they're compared."

Here's an example from the documentation:

_.differenceBy([1, 2, 3, 5, 6], [1, 2, 3, 8, 10], Math.floor); // [5, 6]

In this scenario, Math.floor() is being used.

let iter_floor = (value) => {
    return Math.floor(value);
};

let differenceBy = _.differenceBy([1, 2, 3, 5, 6], [1, 2, 3, 8, 10], iter_floor);
console.log(differenceBy); // [5, 6]

However, when I try the following:

let iter_greater = (value) => {
    return value > 5;
};

let differenceBy = _.differenceBy([1, 2, 3, 5, 6], [1, 2, 3, 8, 10], iter_greater);
console.log(differenceBy); // []

An empty array is returned instead of the expected values greater than 5.

You can find the source code for lodash differenceBy here: https://github.com/lodash/lodash/blob/4.17.5/lodash.js#L6971

Could someone provide me with an example of how to write an iteratee function for this specific case?

Thank you.

Answer №1

When utilizing a function that includes a comparison, you generate two arrays filled with boolean values.

This particular example showcases:

_.differenceBy([1, 2, 3, 5, 6], [1, 2, 3, 8, 10], iter_greater);

The process unfolds in the following manner:

  1. Map all values and apply the iteratee function iter_greater

    [1,  2,  3,  5,  6]  ->  [false, false, false, false,  true]
    [1,  2,  3,  8, 10]  ->  [false, false, false,  true,  true]
    
  2. Filter the initially mapped array by checking for presence in the second array.

    [false, false, false, false,  true]  first array
    [false, false, false,  true,  true]  second array
     false                               exists in 2nd array
            false                        exists in 2nd array
                   false                 exists in 2nd array
                          false          exists in 2nd array
                                  true   exists in 2nd array
    
    [                                 ] // no values, 2nd array contains true and false
    

Answer №2

differenceBy will iterate through each value using the specified function, keeping only those that return unique values. Since your iter_greater function only returns true or false, which are not unique, it results in an empty array.

An alternative approach that may work in most cases is shown below:

let iter_greater = (value) => {
    return value > 5 ? value : undefined;
};

let differenceBy = _.differenceBy([1, 2, 3, 5, 6], [1, 2, 3, 8, 10], iter_greater);
console.log(differenceBy); // []
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2023282d3f240c78627d7b7e">[email protected]</a>/lodash.min.js"></script>

However, you may encounter issues with the following scenario:

let iter_greater = (value) => {
    return value > 5 ? value : undefined;
};

let differenceBy = _.differenceBy([1, 2, 3, 5, 6], [], iter_greater);
console.log(differenceBy); // []
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2cecdc6c3d1cae2968c93958c97">[email protected]</a>/lodash.min.js"></script>

A more suitable solution would be to combine _.difference and .filter methods as follows:

let differenceBy = _.difference([1, 2, 3, 5, 6], [1, 2, 3, 8, 10]).filter(x => x > 5);
console.log(differenceBy); // []
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81edeee5e0f2e9c1b5afb0b6afb4">[email protected]</a>/lodash.min.js"></script>

Answer №3

Try out this code snippet:

const roundDownIfAboveFive = (value) => {
 return value > 5 && Math.floor(value);
};

const differenceOfArrays = _.differenceBy([1, 2, 3, 5, 6,7,8,9], [1, 2, 3, 8, 10], roundDownIfAboveFive);
console.log(differenceOfArrays); // [6, 7, 9]

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

Assortment of versatile containers

When working with a map of Entry objects and having an array in a class, I wondered if it was necessary to use a typecast as my instructor suggested. Here is the code snippet: private Entry<K,V> array; After initializing the array with: array = ne ...

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...

The Process of Developing Applications

As a newcomer to web development, I have a solid understanding of HTML and CSS, and am learning JavaScript. When considering creating a web app, would it be better for me to focus on writing the functionality in JavaScript first before integrating it int ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Scroll with Angular to Move Elements

Is there a way to convert this Jquery Code into an angularJs directive? http://jsfiddle.net/MMZ2h/4/ var lastScrollTop = 0; $("div").scroll(function (event) { var st = $(this).scrollTop(); if (st > lastScrollTop) { $('img').a ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...

Performing a basic arithmetic calculation

I've encountered a simple math problem that is stumping me right now (probably due to being tired from work). The task at hand is straightforward - I need to loop through items and display the final price without taxes, discounts, etc. While my mathem ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

"Quickly clearing the terminal in Java Script with shortcut keys - a step-by-step guide

This GDS command is specifically designed to run on the Travelport terminal through API. Each command generates a response, and typing "clear" in the terminal will clear it. However, I am looking for a shortcut like (Ctrl + any key) to achieve the same fun ...

What is the process for securing a photo to a canvas?

I have included <input type='file' id="image"> in my HTML code. How can I display the uploaded image on my canvas using p5.js? What is the best way to add an event listener to this action and transfer the uploaded file onto the ca ...

Displaying data in a tabular format using an array

Almost finished with this, but encountering the following issue: <table border="1" cellpadding="2"> <thead> <tr> <th>Item Code</th> <th>Description </th> ...

JavaScript CompleteLink message

Hey there, I've come across a JavaScript code for a countdown timer but need some assistance with it. The issue I'm facing is that within the code, there's a line that displays a message to the user when the timer reaches zero. I want to kn ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

Incomplete data retrieval issue encountered during .ajax call

I am having trouble retrieving all 4 key|value pairs from a page that displays an object as text in the body and pre tag. It seems to be missing one pair - any ideas why? Just a heads up, I've tweaked some of the URLs and data in the JSON output for ...

Determine the most similar JSON array

My dataset is in JSON format, { "a": ["73.0", "41.0", "98.0", "43.0"], "s": ["74.0", "43.0", "112.0", "44.0"], "f": ["75.0", "45.0", "116.0", "45.0"], "l": ["76.0", "47.0", "120.0", "46.0"], "x": ["77.0", "49.0", "128.0", "47.0"], "q": ["78.0", "51. ...

Utilizing AngularJS to Retrieve URL Parameters Within a Controller

I am attempting to retrieve URL parameters in my controller: Although I came across this example, I encountered an error that appears to be connected to the loading of necessary modules. app.controller('WidgetCtrl', ['$scope', '$ ...

Validation of the length for masked input fields

Below is an example of a masked field: <input id="phone1" placeholder="(___) ___-____"/> The masking is achieved using the code snippet below: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jq ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...

Does using array.push(val) to push values into an array in AngularJS result in creating a deep copy?

Is a deep copy of the pushed value created inside the array when using array.push() to add values at the end in AngularJS? ...