1

I do not know if the question should be directed to typescript or angular 2

how get return of forEach in angular 2?

I have the following:

let info = this.array.forEach((i, index) => {
    .....
    .....
    return res;

});

console.log(info);

Has returned -> undefined

Does anyone know how to get this return?

Jobsdev
  • 1,047
  • 3
  • 11
  • 28
  • 1
    use `.map`. instead. – Seiyria May 04 '17 at 17:19
  • There's no such thing as a return of [`forEach`, as the documentation shows](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=control). Or rather, you are getting the one and only return value, `undefined`. – Heretic Monkey May 04 '17 at 17:21
  • Foreach is used to carry out side effects, not return values. Use `map` to map one array to another using a function, which seems to be what you're trying to do here. – Carcigenicate May 04 '17 at 17:21
  • 1
    *I do not know if the question should be directed to typescript or angular 2* Neither. It's plain old JavaScript. –  May 04 '17 at 17:26

1 Answers1

3

Javascript array comes up with inbuilt function called map, filter etc..So you can use map to iterate through values in array.

 let info = this.array.map((res,key) => {
        //key can also be accessible
        return res;

    });

    console.log(info);
Pramod Patil
  • 2,704
  • 2
  • 14
  • 20