When using array.filter(), falsey values are excluded in a function expression, however, they are not excluded when using an arrow function

Currently, I'm tackling a challenge that involves the array_diff function, which aims to retrieve values from array a that also exist in array b.

Having recently learned about the advantages of named function expressions for console debugging over anonymous fat arrow functions, I decided to approach this problem by creating a named function called removeDuplicate to filter my array.

Despite my efforts, I've encountered an issue where the filter function unintentionally eliminates the falsey value 0 from the output array.

This is the structure of the named function expression:

function array_diff(a, b) {
  return a.filter(function removeDuplicate(x) { if(b.indexOf(x) == -1) return x; });
}

array_diff([0,1,2,3,4],[2,4]); // [1, 3]

And here is the same logic implemented using an Anonymous Fat Arrow function:

function array_diffTwo(a, b) {
  return a.filter((x) => { return b.indexOf(x) == -1 });
}

array_diffTwo([0,1,2,3,4],[2,4]); // [0, 1, 3]

I'm seeking clarification on why the falsey value 0 gets removed in array_diff but not in array_diffTwo. Any insights would be greatly appreciated!

Answer №1

The issue lies in the fact that when you use return x in the filter callback, if x (the current item being processed) evaluates to falsey, it will not be included in the final array, regardless of whether the condition b.indexOf(x) == -1 is met or not.

To rectify this problem, follow the same approach as shown below:

return b.indexOf(x) == -1

function array_diff(a, b) {
  return a.filter(function removeDuplicate(x) { return b.indexOf(x) === -1 });
}

console.log(array_diff([0,1,2,3,4],[2,4])); // [0, 1, 3]

(On another note, arrow functions are not used in the code snippet provided)

To optimize the computational complexity from O(n^2) to O(n), consider creating a Set of values from array b instead of repeatedly checking for indexOf on every iteration:

function array_diff(a, b) {
  const bSet = new Set(b);
  return a.filter(function removeDuplicate(x) { return !bSet.has(x); });
}

console.log(array_diff([0,1,2,3,4],[2,4])); // [0, 1, 3]

Answer №2

There seems to be a misconception in how the array.filter(callback) method works. The callback should act as a predicate, where you return true for the elements you wish to keep and false for the ones you want to remove. By returning the elements themselves, it results in elimination of falsey elements.

Furthermore, an arrow function should look something like this:

array_diff =(a,b)=>a.filter(x=>b.indexOf(x)<0)
console.log(array_diff([0,1,2,3,4],[2,4]))

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 obtain the id of a selected row using JavaScript?

I'm attempting to utilize the JavaScript function below to extract a specific cell value from a jqgrid upon clicking. Within the following function, #datagrid refers to the table where the jqgrid is located. $("#datagrid").click(function ...

The functionality of $render ceased to operate effectively with the release of angular 1.2.2, particularly in relation

Yesterday, I upgraded from angular 1.0.8 to angular 1.2.2 and encountered a problem where the $render function in the directive below is no longer firing, despite fixing other issues that arose. Has anyone else experienced this issue before? ...

Having trouble retrieving the data from a post request in Express

I'm encountering an issue while attempting to access the data in a POST request. Even after using console.log(req.body), I only receive an empty {}. My suspicion is that the error may lie somewhere within the markup? Below is the relevant client-sid ...

What is the best way to divide a single-item object array into three separate objects?

Here is the data structure for the response data: const res = { data: [{ name: 'c2', ipaddr: '192.168.1.5', port: 4435, sshuser: "abc", sshpass: "xyz", sshport: 22, license: 'licens ...

Error: Attempting to delete a dynamically allocated array with an invalid pointer is causing a

Currently experimenting with pointers arithmetics and puzzled by the "free(): invalid pointer" error that arises when executing the final line containing delete [] arr;. I've noticed that this code runs smoothly when using C4Droid on my Android phone ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

Angular allows for the editing of a table by double-clicking and using an array of objects

I am dealing with an array of objects structured like this: $scope.rows = [{ num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 8 ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

How to update an object property in React using checkboxes

I am currently navigating the world of react and have encountered a challenging issue. I am in the process of developing an ordering application where users can customize their orders by selecting different ingredients. My approach involves using checkboxe ...

Create a graph with Javascript

I successfully created a chart using JavaScript with hardcoded data in the code snippet below. However, I am facing an issue with integrating this code to work with AJAX data instead of hardcoded data. Code: window.onload = function () { var c ...

Sort a JSON object in ascending order with JavaScript

I have a JSON object that needs to be sorted in ascending order. [{ d: "delete the text" }, { c: "copy the text" }] The keys d and c are dynamically generated and may change. How can I sort this into? [{ c: "copy the text" }, { d: "delete the text" }] ...

Using JS/AJAX to update a section of a webpage when a button is clicked

Currently, I am working on developing a generator that will display a random line from a .txt file. Everything is going smoothly so far, but I have encountered an issue - I need a specific part of the page to refresh and display a new random line when a ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Updating Vue.js asynchronously using JavaScript import

I am facing a challenge with two form components that share a common JS validator. import { validateInput } from './validateInput.js' export default { data () { return { email: '<a href="/cdn-cgi/l/email-protection" class="_ ...

What is the best way to notify my form that a payment has been successfully processed?

I'm working on a form that has multiple fields, including a PayPal digital goods button. Clicking on this button takes the user out of the website's workflow and into a pop-up window for payment processing. Once the payment is completed, the retu ...

Check to see if the variable is present in LocalStorage using Javascript

Currently working on a chat system where I create a Localstorage variable whenever a new chat is initiated. Here's how I do it: localStorage.setItem("chat_"+varemail, data); My next step is to figure out how many of these chat variables exist. Somet ...

Issues with code execution in JavaScript caused by faulty Regex expressions

Looking for a solution to create a capture and test program for a unique date format that isn't compatible with Date.parse (results in NaN) using the following RegEx: /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/ //day/month/year While ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Embedding JavaScript directly into a Jade file(Note: This is

After spending about 3 hours trying to unravel the mystery, I'm still lost and unsure where to even begin looking for answers. We implemented a method that allows us to include JS files directly in a single Jade file, serving as a manifest for all ou ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...