Entry Guy
Entry Guy

Reputation: 475

Push array from function which places into another function

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())

Upvotes: 0

Views: 47

Answers (1)

kind user
kind user

Reputation: 41893

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();

Upvotes: 3

Related Questions