Looking for help with the .filter() method?

Have you ever wondered why adding curly braces to the filter argument causes it to not work as expected? Let's explore this issue further.

// Dive into your code here:
function justCoolStuff(arr1,arr2){
  var newArray = arr1.filter(word => {arr2.includes(word)});
  return newArray
}

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff)

It might seem strange that when the curly braces are removed, the code runs smoothly. After all, shouldn't it be correct syntax since we are using a function? Share your thoughts on this!

// Dive into your code here:
function justCoolStuff(arr1,arr2){
  var newArray = arr1.filter((word) => arr2.includes(word));
  return newArray
}

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff)

Answer №1

In order to find out if a word is included in an array, make sure to use the return statement followed by arr2.includes(word)

Answer №2

When you include curly braces, the automatic return feature no longer functions as expected. In this case, you must manually specify the return value like so:

let filteredArray = arr1.filter(item => { return arr2.includes(item) });

For more information on arrow functions, you can check out the basic syntax documentation.

Answer №3

Maybe you'll find it easier to grasp if you reorganize it like this -

let newArray = arr1.filter(word => {arr2.includes(word)});

let newArray = arr1.filter(word => {
  arr2.includes(word)
});

Viewing it in that way, you can see that the missing piece is the return statement. When using curly braces, the use of return must be explicit.

Answer №4

When the arrow is followed by curly braces, it signifies the block of function code that will be carried out. In the initial scenario mentioned, there is no explicit return statement provided, indicating that nothing is being returned. On the contrary, in the second scenario utilizing this syntax, it is implicit that the boolean value is being returned, aligning with the expectations of the filter method.

Answer №5

When using braces in JavaScript, they are often treated as the start of a function and require an implicit return statement.

However, there are ways to use braces without needing to return, as demonstrated below:

// Implementing a function that filters out items from one array that are also present in another array:

function justCoolStuff(arr1,arr2) {
    var newArray = arr1.filter(word => {
        return arr2.includes(word);
    });
    return newArray;
}

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff))

Note the following syntax comparisons:

function doSomehting() {
  return 1;
}

// is equivalent to
const doSomething = () => 1;

// also equivalent to
const doSomething = () => {
  return 1;
}

// but not equivalent to
const doSomething = () => {
  1
}

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

`Scrolling through a horizontal menu with no scrollbar present`

Is there a way to create a horizontal menu that can scroll left or right without the scrollbar? I'm looking for a solution like adding on-screen arrow buttons or implementing mouseover functionality. What would be the best approach? div.scrollmenu ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...

A guide to reversing video playback with react-native-video

I am looking to create a unique video experience where the video plays for 15 seconds in a forward order, then automatically switches to playing in reverse. In my code snippet below, I am fetching a local video file and using react-native-video to displa ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

Tips for dynamically adjusting the size of a div container according to the user's

I have been working on a unique landing page design featuring a menu made up of custom hexagons. I aim to make these hexagons dynamically adjust to fill the entire screen based on the user's resolution, eliminating the need for scrolling. For a previ ...

What is the best way to combine two arrays of objects with varying values for the same key, and add a new object to the mix?

I have two arrays: arr1 = [ { "OwnershipNumber": 0, "ID": null, "Name": "Contractor LLC", "ContrEmployeeTypeId": 0, "ContactEmail": "", "ContactPhone": "", "VeteranEmployeeMilitaryAffiliation": "", "SocialSecurityNumber": ...

Material UI autocomplete bug: a frustrating issue with suggestions

I'm currently developing a single-page application using React, and I have a shipment page where multiple products and their quantities need to be added. I've implemented some functions for this scenario, and while they are working correctly (sen ...

Using Jquery to assign negative values in CSS styling

Here is the jQuery code snippet I am working with: <script type="text/javascript" src="js/jquery.js"> </script> <script type="text/javascript"> $(document).ready(function() { get_font_size(); set_sidebar(); }); function get_f ...

Looking for assistance with designing a responsive login box

Greetings! I'm a beginner in programming, so please excuse me if my issue seems simple. I have a website with a login form, but I am struggling to make it responsive. Every time I attempt to do so, the entire layout gets messed up. Could someone kin ...

Click to dynamically change the input number variable

I'm in the process of creating a special calculator, where you input the number of years into a field, hit submit, and see different results displayed below without the page reloading. All my calculations are working properly at the moment. However, ...

Updating array object properties within nested for loops in JavaScript can be challenging

Exploring nested loops: for(let i = 0; i < availabilities.length; i++){ if(availabilities[i].round === 1){ // Identify objects with the same event_team_user_id and update status property let indices = helperService.findArrayIndices( ...

invoking a function from a parent controller within an EXTjs application using an Iframe

Hey everyone, I could really use some help with this seemingly simple issue: I've been tasked with editing an EXTjs application that already exists. Within this application, there is a point where an iframe is loaded to call an external HTML file as ...

Differences between Typescript React.ReactElement and JSX.Element

Simple Inquiry: I'm curious about the contrast between React.ReactElement and JSX.Element. Can you clarify if they are interchangeable, and advise on when to opt for one over the other? ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

The issue persists as AJAX data and text box data are not being saved simultaneously

I need assistance with an Ajax setup. I am trying to pass the screenwidth information along with a user input value from a text box to a PHP page. However, I am encountering issues as the only value being passed is from the textbox and the other one is sho ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...