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

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

PHP code to eliminate elements from an array that fall within a specific time range

I am attempting to retrieve elements from an array based on a specified criteria where the values fall within a time range but yield no results. Here is an example of the source array: Array ( [0] => Array ( [start] => 12:00:00 ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

Can jQuery help me identify which <input type='image> was clicked within a form containing several submit images?

Consider this hypothetical scenario: <form> <input type="text" name="some_name" value="val" id="some_name"> <input type="image" value="action" alt="Add To Cart" name="add" src="/images/submit.gif"> <input type="image" value="act ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Retrieve nested JSON data from an AJAX request

Currently, I am working with an API that provides JSON data back to me. The challenge I'm facing is figuring out how to access this data and showcase it on my HTML webpage since the results are stored in server memory rather than a file. Below is an e ...

"Enhancing web interactivity with AJAX requests and dynamic functionality in web

I'm finding it hard to understand the distinction between Rich Internet Applications and AJAX calls. From what I gather, any application that requires client-side execution can be classified as RIA. So, by this definition, should this website be cons ...

The chaotic world of Android WebKit versions 2.x and 3.x

I have been working on an Android app and my goal is to make it compatible with Android versions 2.2 and above. Currently, due to issues with the WebView control, I am restricted to targeting Android 4.0 and higher. The app primarily uses HTML, CSS, Java ...

Is it a wise decision to provide the client with a new token just one minute before the expiration of the old one?

When monitoring my backend, I constantly check the remaining time before the JWT expires, which is set to 15 minutes. If there is only one minute left or less, I generate a new JWT and include it in the response header as a setToken. The front-end can then ...

Tips for transferring the value of a text box between components bidirectionally in Angular 8

Let's create a scenario where we have two components: login and home. The goal is to capture the value entered in the text box of the login component and pass it to the text box in the home component when the "proceed" button in the login component is ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

The element is implicitly assigned to an 'any' type due to the inability to use a 'string' type expression to index the 'Breakpoints' type

I have a question related to TypeScript that I need help with. My objective is to create a custom hook for handling media queries more efficiently. Instead of using useMediaQuery(theme.breakpoints.down('md');, I want to simplify it to: useBreakP ...

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

Setting an array of objects using TypeScript in the useState hook: A step-by-step guide

const response = { results: { items: [ { name: 'item1', }, { name: 'item2', }, { name: 'item3', }, { ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. https://i.sstatic.net/XldZC.png For ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective: For Value 1, the CSS class should be badge-primary For Value 2, the CSS class should be badge-secondary For all other values, use the CSS class badge-danger This functionality is implemented in the handleChange function. Issue: Current ...