Andrew Graham-Yooll Andrew Graham-Yooll - 2 months ago 18
TypeScript Question

Returning from .filter nested within .ForEach

I have this code that i have been figuring out by trial and error:

let _fk = this.selectedIaReportDiscussedTopic$
.map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"]
.forEach((fk) => {
let surveyAnswerMatches = this.surveyAnswers.filter((sa) => {
return fk === sa._id
console.log('surveyAnswerMatches', surveyAnswerMatches)//[object] <- this contains what I want and so I return it below, but nothing shows in console.log(_fk)
return surveyAnswerMatches

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

What I want, is to be able to access the surveyAnswerMatches array from outside of the function. I thought returning the array would allow me to access it through the _fk variable.

How come the return value does not get assigned to _fk?

What would allow me to access the surveyAnswerMatches from out outside all the .forEach and .map calls?

Thanks SO community!

Edit: More Info

console.log('this.selectedIaReportDiscussedTopic$', this.selectedIaReportDiscussedTopic$) //[{_id: "discussed_topic_2016-11-03T11:48:48Z_1", fk_surveyanswer:"surveyanswer_2016-11-03T11:48:48Z_1" }]
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)// This is what I get [[{_id:"surveyanswer_2016-11-03T11:48:48Z_1", foo: "someotherbar"}]]
console.log('this.surveyAnswers', this.surveyAnswers)// [{_id:"surveyanswer_2016-11-02T13:29:26Z_1", foo: "bar"}, {_id:"surveyanswer_2016-11-02T15:34:41Z_1", foo: "somebar"},{_id:"surveyanswer_2016-11-03T11:48:48Z_1", foo: "someotherbar"}]


Simply use a closure to access a variable you defined before calling the mapping and forEach:

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

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

Edit: cleaned up the code