J.lan
J.lan

Reputation: 223

for each does not work on object array when you filter

I m trying to get all the numbers from the list of all the contacts. Im probably not using forEach correctly any advice? I've put a sample of what is expected

 //sample of a contact
  Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
  Object {
    "countryCode": "us",
    "digits": "5557664823",
    "id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
    "label": "work",
    "number": "(555) 766-4823",
  },
  Object {
    "countryCode": "us",
    "digits": "7075551854",
    "id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
    "label": "other",
    "number": "(707) 555-1854",
   },
 ],
},

//Expected
numbers = [
   5557664823,
   7075551854
]

//does not work 
const numbers = contacts.map(contact => contact.phoneNumbers.forEach(number));

Upvotes: 0

Views: 38

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

forEach always returns undefined, so your map callback returns undefined, so numbers will be full of undefineds.

I think you probably want to return the phone numbers (each number in the phoneNumbers array of each entry), and then perhaps flatten the result:

const numbers = contacts.map(contact => contact.phoneNumbers.map(({number}) => number)).flat();

Array.prototype.flat is relatively new, but easily polyfilled.

That's such a common pattern that there's a flatMap method to do it in one go:

const numbers = contacts.flatMap(contact => contact.phoneNumbers.map(({number}) => number));

Or just a simple loop with push:

const numbers = [];
for (const {phoneNumbers} of contacts) {
    numbesr.push(...phoneNumbers.map(({number}) => number));
}

Upvotes: 2

bknights
bknights

Reputation: 15377

I don't know how many times I've done that. forEach doesn't return anything.

const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers)),[]);

or

const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers.map(pn=>pn.number)),[]);

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Probably want to use reduce and map

let numbers = contacts.reduce((p, c, i) => {
    return p.concat(c.phoneNumbers.map(pn => pn.number));
}, []);

Upvotes: 0

Related Questions