map did not return array when has an inner loop

const testTrue = sample.map((condition) => {
  return Object.values(objects).forEach(value => {
    return someFunc(condition.abc, value)
  })
});

sample is an array, why above code don't make testTrue become [ true, false ] ? I got undefined, is it because of forEach here?

This is working

const testTrue = sample.map((condition) => {
  return someFunc(condition.abc, value)
});

1 answer

  • answered 2018-07-12 06:34 chŝdk

    Actually, Array#forEach() doesn't return anything, if you take a look at the Array#forEach() MDN Specifictaion you can see that its ReturnValue is undefined.

    And that's why the map call isn't returning any element, in your code:

    const testTrue = sample.map((condition) => {
      return Object.values(objects).forEach(value => {
        //The following will be ignored
        return someFunc(condition.abc, value)
      })
    });
    

    The call to return someFunc(condition.abc, value) is useless and it is as if you weren't writing anything.

    Solution:

    You can change the forEach() with an Array#map() call to return transformed elements of your array:

    const testTrue = sample.map((condition) => {
      return Object.values(objects).map(value => {
        return someFunc(condition.abc, value)
      })
    });