Reputation: 475
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
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