0

I have a questions about nested functions

How can I get b array which contains [1, 2, 3] here:

function someFunc() {
  const a = [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
  const b = []
  
  function someOtherFunc() {
    a.forEach(i => {
      b.push(i.id)
    })
  }
  return b
}

console.log(someFunc())

1
  • 2
    you aren't calling someOtherFunc anywhere... Commented Mar 13, 2017 at 22:17

1 Answer 1

3

You are getting an empty array, because the someOtherFunc function wasn't executed.

function someFunc() {
  const a = [{ id: 1}, { id: 2 }, { id: 3 }];
  let b = [];
  
  someOtherFunc();
  
  function someOtherFunc() {
    a.forEach(i => {
      b.push(i.id)
    })
  }
  return b
}

console.log(someFunc())

Or quicker solution, using Array#map.

function someFunc() {
  console.log([{ id: 1 }, { id: 2 }, { id: 3 }].map(v => v.id));
}

someFunc();

Sign up to request clarification or add additional context in comments.

2 Comments

Might be worth mentioning that return a.map(...) would be much more efficient here.
No.. I meant completely remove someOtherFunc() and b altogether... This function can be 2 lines long

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.