2
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)
});
3
  • 4
    The value returned to the forEach callback is ignored. What were you trying to do there? Can you give an example of condition and objects and your expected output? Commented Jul 12, 2018 at 6:29
  • Can you also provide info on what will be present in sample array? Commented Jul 12, 2018 at 6:36
  • please post your someFunc definition and how you want the result Commented Jul 12, 2018 at 7:38

1 Answer 1

3

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)
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

I got array within array using your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.