I have an array of objects:
let reports = [{ inbound_calls: [...], outbound_calls: [...], outbound_national_calls: [...] },...];
What is the best way to create a new array and assign into a variable:
1st approach - one loop:
let inbound_calls = []; outbound_national_calls = [], outbound_calls = [];
reports.forEach((e) => {
inbound_calls.push(e.inbound_calls);
outbound_national_calls.push(e.outbound_national_calls);
outbound_calls.push(e.outbound_calls);
})
2nd approach:
let inbound_calls = this.reports.map((report) => report.inbound_calls)
let outbound_national_calls = this.reports.map((report) => report.outbound_national_calls)
let outbound_calls = this.reports.map((report) => report.outbound_calls)
I'm starting to learn functional programming, and want to apply it to my code, I would go with first approach (one loop), but as I did research about functional programming I think the second one is the right way (much cleaner) but, I'm not sure, what is less expensive operation?
forEach()loop will be the less expensive operation. If performance is an absolute necessity, the traditionalfor()loop is the fastest loop in the JS runtime.inbound_calls = reports.inboundCalls.slice(). However, I think the question still has merit, probably it would make more sense ifreportscontains something like[ { inbound_calls: ...} ]