Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error:

let _fk = this.selectedIaReportDiscussedTopic$
        .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) 
        .forEach((fk) => { 
            let surveyAnswerMatches = this.surveyAnswers.filter((sa) => {
                return fk === sa._id
            })
            console.log('surveyAnswerMatches', surveyAnswerMatches)
            return surveyAnswerMatches
        })

    console.log('this is fk', _fk) 

I am trying to access the `surveyAnswerMatches` array from outside of the function. However, even though I thought returning the array would allow me to access it through the `_fk` variable, the return value does not get assigned to `_fk`.

How can I access the `surveyAnswerMatches` from outside all the `.forEach` and `.map` calls?

Thank you to the SO community for your help!

Edit: Additional Information

console.log('this.selectedIaReportDiscussedTopic$', this.selectedIaReportDiscussedTopic$) 
let surveyAnswerMatches = this.selectedIaReportDiscussedTopic$
            .map((discussionTopic) => {return discussionTopic.fk_surveyanswer})
            .map((fk) => { 
                return this.surveyAnswers.filter((sa) => {
                    return fk === sa._id
                })
            });

   console.log('this is surveyAnswerMatches', surveyAnswerMatches)
   console.log('this.surveyAnswers', this.surveyAnswers)

Answer №1

To access a variable before calling the mapping and forEach, you can simply use a closure:

let matchingSurveys = [];    
this.selectedIaReportDiscussedTopic$
        .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"]
        .forEach((fk) => { 
            matchingSurveys.push(this.surveyAnswers.filter((sa) => {
                return fk === sa._id;
            }));
        });

console.log('Matching surveys:', matchingSurveys);

Edit: Code has been cleaned up.

Answer №2

Why doesn't the value returned by the callback function get assigned to _fk?

The reason is that the return value of the callback function passed into the forEach method has no impact on what forEach itself returns (which is nothing, hence using its return value will give you undefined).

When you mention "the return value," it's important to clarify which specific return value you are referring to since the callback function gets called repeatedly for each entry in the array.

If you want to capture and utilize the return values from the callback function for each item in the array, consider replacing the forEach with a map method instead. This way, you will have an array containing the surveyAnswerMatches for each element in the original array.

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

Is there a way to update the state for a specific location on a map?

I have a requirement to update the quantity of a product by using setCount. let [product.quantity, setCount] = useState(product.quantity); Implementing increment and decrement functions for product.quantity const increaseQuantity = () => { setCoun ...

What is the best way to run multiple functions from an object?

My goal is to call all the functions that are contained within an object. const data = { fruits: funcA(), vegetables: funcB(), bread: funcC(), } The desired result looks like this: firstFunc(); dispatch(funcA()); dispatch(funcB()); dispatch(funcC() ...

Processing of an array received via AJAX and passed to a PHP script, inside a separate function in a different file

I have a JavaScript array that I am sending via AJAX to a PHP file named aux.php. What I want is for this array to be visible and manipulable within a function inside a class in another PHP file called payments.php. I've provided all the code so they ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

What is the method to modify an action in an Ajax function?

I am trying to modify the action in the AjaxUpload function. The issue is that the value of setnamefile in the action does not change because the page does not reload. My idea was to change the action on submit, but I have not been able to do so successfu ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

Tips for inserting an item into the parent window: Chrome-specific (compatible with all other browsers)

In my HTML file, I have an iFrame element like this: <iframe src="frame.html" width="2000" height="1000"></iframe> When trying to use jQuery's append function from within the iFrame to add a DIV to the parent window, it works fine in Fir ...

Steps for creating a basic prioritized event listener system in JavaScript

I am currently working on an event/listener manager that has the following function: var addListener = function(event, listener) { myListeners[event].push(listener); //assume this code works } However, I now need to modify it so that it appears a ...

"Access denied" error when using Internet Explorer and jQuery

Attempting to make an AJAX call using jQuery's $.post in Internet Explorer is resulting in an error message stating "Permission denied." This peculiar issue only seems to occur when accessing a page after having visited another page. For example, if ...

Creating a reusable anonymous self-invoking function

Here is a function that I am working with: (function(e, t) { var n = function() { //code, code, code }; //code, code, code e.fn.unslider = function(t) { //code, code, code }; })(jQuery, false) To execute this function, I have impleme ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

Middleware in Express.js designed to alter the response object

One method I'd like to explore is using middleware functions to alter the response. app.use(function(request, response, next) { .. do something .. next(); // moves to next middleware }); When it comes to modifying the request and response ob ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

There seems to be a problem with the text-to-speech API: It looks like there's a ReferenceError stating that

Currently, I am developing a program using the Quasar framework which is based on Vue and can be compiled for mobile using Cordova. However, I am encountering some issues when trying to run it on mobile. Below is the function causing problems: activat ...

Angular - passing information to a nested component

Within my application, I have a main component along with three sub-components. I am passing data to these three sub-components and using setTimeout to manage the timing of the data being sent. The first sub-component displays for 5000 milliseconds. The ...

Error 404: "Headers already sent to the client cannot be modified"

I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve. This is my approach: app.get("/projects", t("projects", function(req, res) { res.header("Cache-Control", "private ...