0

Using javascript Array methods, I want to flatten this:

accounts: [
                {
                                id: 129,
                                contacts: [932, 552, 803]
                },
                {
                                id: 433,
                                contacts: [932, 606]
                }
]

into this:

[932,552,803,606]

Notice the unique contacts. Any solutions?

Dewey
  • 904
  • 1
  • 10
  • 21
  • What have you tried so far? Where are you stuck? It should be pretty simple to iterate over `accounts` and add `contacts` to a dictionary and then finish by turn the dictionary into an array. For example. – Matt Burland Jul 10 '20 at 15:09

4 Answers4

1

I think this is what you are look for , you just need to loop the arrays and use array.push method to push into the res array if it is not present

var accounts = [
                {
                     id: 129,
                     contacts: [932, 552, 803]
                },
                {
                     id: 433,
                     contacts: [932, 606]
                }
             ]

var res =[];
accounts.forEach(obj => obj.contacts.forEach(ob=> {

if(!res.includes(ob)){res.push(ob)}
}))

console.log(res);
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

Do a little mapping and call es6 feature Set

let accounts =[
  {
    id: 129,
    contacts: [932, 552, 803]
  },
  {
    id: 433,
    contacts: [932, 606]
  }
]

var contacts = [];

accounts.map(function(item){
    return item.contacts.map(function(contact){
    contacts.push(contact)
  })
})

contactsWithNoDups = Array.from(new Set(contacts));

console.log(contactsWithNoDups);
BryanOfEarth
  • 715
  • 11
  • 26
0

Or, two ways of doing it as a one-liner:

const accounts= [{id: 129, contacts: [932, 552, 803]},
                 {id: 433, contacts: [932, 606]}],
 r1=Object.keys(accounts.reduce((a,{contacts})=>(contacts.forEach(c=>a[c]=1),a),{})).sort(),
 r2=[... new Set(accounts.reduce((a,{contacts})=>a.concat(contacts),[]))];

console.log('r1:',r1);  
console.log('r2:',r2);
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

I'd go for a simple readable format as this one :

let uniqueIdsCollection = new Set();
accounts.map(account => account.contacts.map(id => {
  if (!uniqueIdsCollection.has(id)) {
    uniqueIdsCollection.add(id);
  }
}));

But yeah, there is already plenty of documentations and subjects on the matter ... you could have done a bit of research before posting I guess

Alex
  • 4,599
  • 4
  • 22
  • 42