The filtering function does not provide any output

When working in JavaScript, I often find myself needing to filter a list of objects

let dataid = infosStructured.filter(elm => {
  console.log(elm.identifiant);
  console.log("matching value", elm.identifiant == this.dataService.getcurrentId()); // This condition is met
  return elm.identifiant == this.dataService.getcurrentId();
});
console.log(dataid); // However, the result is empty

It's peculiar that even though

elm.identifiant == this.dataService.getcurrentId()
evaluates to true at some point, my dataid remains empty

Answer №1

There is no correlation with the concept of functional-programming. Check out the following code snippet for clarity:

let f = a => { a == 1 };
f(1); // undefined
let g = a => a == 1;
g(1); // true
let h => a => { return a == 1; };
h(1); // true

Avoid using inlined functions for debugging higher order functions.

Answer №2

When working with multi-line code inside the Array.filter() method, it is necessary to explicitly include the return keyword. However, for single-line code like

infosStructured.filter((elm) => elm)
, the return keyword is not required.

let dataid = infosStructured.filter(elm => {
  console.log(elm.identifiant);
  console.log("matching value", elm.identifiant == this.dataService.getcurrentId()); // I get a true value
  elm.identifiant == this.dataService.getcurrentId();
  return elm;
});
console.log(dataid);

If you do not need the console.log() statements inside the filter, you can simplify it into a one-liner without the return keyword like this:

let dataid = infosStructured.filter((elm) => elm.identifiant == this.dataService.getcurrentId());
console.log(dataid);

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

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

The Challenge of Dynamic Angular Components

Upon triggering the blur event of the contenteditable div, I observe changes and dynamically generate new strings with additional spans to update the same div accordingly. However, a challenge arises when all text is deleted from the contenteditable div, r ...

All-in-one Angular script and data housed within a single document

Context I want to design a personalized "dashboard" to assist me in staying organized. This dashboard will help me keep track of the issues I am currently handling, tasks I have delegated, emails awaiting response, and more. While I am aware of project ma ...

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

Having difficulty grasping the concept of MVC within the context of my website's code

I'm struggling to grasp the concept of utilizing model-view-controller in the context of my registration system. As far as I understand it, the view loads, displaying the registration HTML form to the user. Once the user submits the form, a JavaScript ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

.post method reveals parameter in URL upon submission

Currently, I am utilizing the $.post method to send a value to a PHP page for processing after replacing the serialize utility with a more specific element: $("button").click(function(event) { $.post( "php/index.php", { seq: $("seq").v ...

Is it possible to identify horizontal scrolling without causing a reflow in the browser?

If you need to detect a browser scroll event on a specific element, you can use the following code: element.addEventListener('scroll', function (event) { // perform desired actions }); In order to distinguish between vertical and horizontal ...

The Concept of Long Polling and How it Impacts Server Function

After spending a significant amount of time working with PHP, I recently discovered the concept of long polling as an alternative to sending periodic ajax requests. I've realized that sending periodic ajax can be resource-intensive, especially when c ...

Can markers be positioned on top of scroll bars?

Looking for a way to display small markers on the scrollbar of an overflow: scroll element, similar to features found in IDEs and text editors like this one: https://github.com/surdu/scroll-marker. I've considered using a pointer-events: none overlay ...

Provide the user with an .ics file for easy access

Recently, I developed an HTML5 application that enables users to download calendar entries in iCal format. These iCals are generated using PHP. Up until now, my method involved creating the iCal file with PHP and saving it to the web server's hard dis ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

The occurrence of an unhandled promise rejection is triggered by the return statement within the fs

In my code, I have a simple fs.readFile function that reads data from a JSON file, retrieves one of its properties (an array), and then checks if that array contains every single element from an array generated by the user. Here is the snippet of code: co ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Guide on Wrapping a File and Piping it to a New File within the Same Directory using Gulp

I'm in the process of developing a Gulp build system that has the following requirements: Extract HTML files from each directory Enclose the HTML files with additional HTML markup Generate a new file named wrapped.html Place the new file back into t ...

Obtain the value of a JavaScript form with a dynamically generated field name

I am struggling with a simple javascript code and for some reason, it's not working. var number = 5; var netiteration = "net"+number; // now netiteration is equal to net5 var formvalue = document.forms.myformname.netiteration.value; Why is this co ...

Different ways to initialize objects in JavaScript (constructor overloading)

Within my Account_Model.js model, I have a set of queries that handle creating, reading, updating, and deleting user accounts (CRUD operations). The constructor I currently have requires passing in parameters such as username, fullname, and password for cr ...

Issues with Videojs Responsive Lightbox Functionality

I am looking for a solution to display VideoJS in a lightbox while keeping it responsive. I came across this helpful code snippet: https://github.com/rudkovskyi/videojs_popup. It seemed perfect until I tried using it with the latest version of Videojs and ...

What causes the issue of undefined destructured environment variables in Next.js?

Within my application built with Next.js, I have configured a .env file containing a variable labeled API_KEY. When attempting to destructure the value of this variable, I am consistently met with undefined, as shown below: const { API_KEY } = process.env ...

Exploring the process of transmitting error codes from a NestJS controller in your application

Is it possible to send error codes in nestjs other than 200? I attempted to inject the response object into a method, but could not find a way to send an error. save(@Body() body: any, @Res() response: Response): string { console.log("posting...&q ...