Transform an array of objects containing nested arrays into a single flat array

I'm looking to flatten the given data structure using Javascript Array methods:

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

So that it becomes:

[932, 552, 803, 606]

Have any ideas on how to achieve this while keeping the contacts unique?

Answer №1

Utilize mapping and leverage the ES6 feature known as Set

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

var uniqueContacts = [];

users.map(function(user){
    return user.contacts.map(function(contact){
    uniqueContacts.push(contact)
  })
})

uniqueContactsArray = Array.from(new Set(uniqueContacts));

console.log(uniqueContactsArray);

Answer №2

I believe this solution aligns with your needs - simply iterate through the arrays and utilize the array.push method to add elements to the res array if they are not already present.

var users = [
                {
                     id: 723,
                     contacts: [543, 878]
                },
                {
                     id: 189,
                     contacts: [543, 987, 332]
                }
             ]

var res =[];
users.forEach(item => item.contacts.forEach(contact=> {

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

console.log(res);

Answer №3

My preference would be for a straightforward and easy-to-read format like this:

const uniqueIds = new Set();
accounts.forEach(account => {
  account.contacts.forEach(id => {
    if (!uniqueIds.has(id)) {
      uniqueIds.add(id);
    }
  });
});

However, there are already numerous resources available on this topic... a little research beforehand could have been helpful.

Answer №4

Here are two concise ways to achieve the same result:

const users= [{id: 229, contacts: [534, 223, 659]},
                 {id: 343, contacts: [984, 345]}],
 r1=Object.keys(users.reduce((a,{contacts})=>(contacts.forEach(c=>a[c]=1),a),{})).sort(),
 r2=[... new Set(users.reduce((a,{contacts})=>a.concat(contacts),[]))];

console.log('r1:',r1);  
console.log('r2:',r2);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Variability in data sizes within Chart.js

I created a sample chart in MS Excel where each data point varies in size according to the legend provided. Can Chart.js accommodate this kind of customization? https://i.sstatic.net/5qjNy.png ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Issue with connecting React Router v4 to Redux - dispatch function not being properly passed

Recently, I've been working on migrating my app to React Router v4 and encountered some challenges due to the significant changes in the API. Here's where I currently stand: Setting Up the Router const createStoreWithMiddleware = applyMiddlewar ...

I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file. <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { ...

Learn how to extract values from an object in Vue JS time-slots-generator and display either PM or AM based on the

Using the time-slots-generator package, I am able to display the time from 0:15 to 24:00. However, the issue is that this package does not have built-in functionality to display AM/PM, so I had to create a manual solution for it. To achieve this, I modifi ...

How to Create an Interactive JavaScript Drop Down List for Displaying and Concealing Divs

Looking for some assistance in combining a chained drop-down list with the functionality to show/hide a specific div based on selection. I've come across solutions for each separately, but struggling to merge the JavaScript code (not my strong suit as ...

Prevent further clicking on a button in a custom Drupal module after it has been clicked three times

I'm new to using Drupal and have created a custom module similar to webform. In my module page, I have two submit buttons and 2 textboxes as shown below: function contact_request($form, &$form_state) { $form ['info'] =array( &ap ...

React Native for Android is failing to display certain images despite them being identical

In my app, I have included a total of 8 images which are stored locally: Background images in 3 different sizes - @1 (~700 kb), @2 (~2.9 mb), @3 (~6.5 mb) 5 other images, each around 100 kb These images are placed randomly on cards that can be slid on ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

Issue with formik onchange event not filling data in Material UI TEXTFIELD component

Greetings! I am currently working on a React project where I am managing the authentication process. I am using Material UI and Formik for validation and handling input changes. However, I encountered an issue with my onchange Formik handler in the TEXTF ...

Display of div content when hovering over table

I am currently developing a simple interactive calendar, and I need some guidance on how to make it more dynamic. Initially, I want only the months to display, but upon hovering over a month, I would like all the individual days to appear. Eventually, user ...

"Mesmerizing Motion: The World of Three

Exploring the world of ThreeJS, I am experimenting with the concept of incorporating multiple objects in a scene and implementing transitions on these objects with the click of a button. While I have grasped the idea of working with multiple objects and a ...

Eliminate an item from a collection of whole numbers

Is there a more efficient way to delete an integer from a list initialized with int list[9999]? I am familiar with removing a specific integer by identifying its key in the list, but this requires shifting all subsequent elements to the left. Given the h ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

Using VueJS to Create a Range of Years from 1900 to Present Year

I'm currently developing a registration form using VueJS, wherein users need to input their date of birth. My challenge is in generating a list of years starting from 1900 up to the current year within a <select> element. Any suggestions on how ...

Adding an exception for ClickAwayListener in React-MUI

Hey there! I'm currently exploring MUI and trying to incorporate the ClickAwayListener API into my project, but I'm facing some difficulties. You can take a look at my project on codesandbox here: https://codesandbox.io/s/react-leaflet-icon-ma ...

Translate the DateTime to the local time zone

As a newcomer to AngularJS, I am working on capturing a DateTime attribute in the UI and passing it to an Odata endpoint. However, the time being sent is not in the current local time. How can I convert this time to local time before sending it to the Odat ...

When working with React, I often encounter situations where I receive very similar Unix timestamps from the `<TextField type="date">` component

I am facing an issue with setting the start date and due date using two Textfield components. Check out the code snippet below: const startDateChange = (e) => { setStartDate(Math.floor(new Date().getTime(e.target.value) / 1000)); console.log(startD ...

Execute the laravel {{action(Controller@method}} by sending a parameter from a vue.js array

Within my view created using Blade templates, I have a link with an href attribute that directly calls a Controller method. Here is an example: <a id="@{{user.id}}" href="{{action('Controller@method')}}">>update</a> Everything wo ...

Utilizing multiple physics simulations in Node.js, failing to optimize server efficiency

My multiplayer game worlds are hosted on AWS using Node and are physics-based (using p2.js), with a physics step rate of 200 steps per second. Each game has its own world and needs to step every 5ms. With only 6-8 players in each game, I can currently hos ...