Generate smaller arrays within a main array

What is the most efficient method for creating sub-arrays from an array? I have an array of objects like this:

bigArray = [
    {
        id: 1,
        name: "Marc",
        age: 29
    },
    {
        id: 2,
        name: "Caroline",
        age: 27
    },
    {
        id: 3,
        name: "John",
        age: 30
    }];

I want to generate 3 sub-arrays:

  • ids = [1, 2, 3]
  • names = ["Marc", "Caroline", "John"]
  • ages = [29, 27, 30]

I've attempted using nested "for" loops and experimented with the map() method, but I'm not convinced it's the most efficient way. Especially since each object may have multiple parameters (such as last name, city, car...)

Answer №1

If all the objects in the array have the same keys, here is one way to approach it:

bigArray = [
    {
        id: 1,
        name: "Marc",
        age: 29
    },
    {
        id: 2,
        name: "Caroline",
        age: 27
    },
    {
        id: 3,
        name: "John",
        age: 30
    }];

let output = {}

Object.keys(bigArray[0]).forEach( key => {
output[key+"s"] = bigArray.map( obj => obj[key] )
})

// Or as a one-liner, to impress your friends
Object.keys(bigArray[0]).forEach( key => output[key+"s"] = bigArray.map( obj => obj[key] ))

console.log(output)

You can then access the data using output.names, output.ages

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

The data retrieved by jQuery AJAX is empty when accessed outside of the success handler

Here is a code snippet to consider: let source = null; fetch('https://example.com/data') .then(response => response.json()) .then(data => { source = data; console.log(source); }); console.log(source) When the fetch request ...

Utilizing Facebook JavaScript across a variety of programming languages

I've integrated a Facebook javascript code snippet into my website, which includes the "like" button and other components. Here is how it looks: <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ ...

Guide on iterating through a three-dimensional array using the foreach loop in PHP

Dealing with a 3-dimensional array in a foreach loop can be tricky. I am struggling to specify which array to echo, as they must be printed in their entirety. Does anyone have a better solution for looping through a 3-dimensional array? This process feels ...

Can you tell me which specific font Adobe Edge Code (Brackets) uses in its code editor?

Can someone please help me? I'm trying to identify the syntax highlighter being used in this code. Is it Prettify or something else? ...

What methods are available for identifying critical points within a 2D array using Python?

My task involves analyzing a large (960,960) array to identify critical points in order to determine local extrema. Despite attempts using np.diff and np.gradient, I have encountered challenges and uncertainty regarding the appropriate function. While np ...

Tips for maintaining a user's login status when the checkbox is selected

I am currently developing a login system that utilizes the modal dialog feature from Bootstrap 3. One of the functionalities I am adding is to allow users to stay logged in if they check a checkbox within the modal dialog. My goal is to keep a user logged ...

What is the best way to designate my field as $dirty within my unique directive implementation?

I have created a custom dropdown/select directive to replace the default select boxes within my form. I also have some buttons that are set to disable while the form remains in its pristine state. app.directive('dropdown', function ($timeout) { ...

accordion effect with a bundle of multi-anchor buttons

Working on a website where I need a navbar or anchor button to display content. Having an issue where all expanded items collapse when clicked for the first time, rather than following instructions as outlined in the JavaScript code. Here is the code snip ...

Exploring JSON Array/Object Iteration in Android Development using Java

Hey Everyone [newbie in the world of Java and Android] I recently wrote a php script that outputs a json response like this echo json_encode(array($camparray)); The format of the json array is as follows: [ { "0":{"url":"10007.jpg","cmpname ...

Compare two arrays in PHP and save the unique strings in a new array

Here are two arrays with values for comparison. Array 1 - reorder_str Array ( [0] => A aacomputational agent is considered intelligent if it can adapt its actions to a particular setting. [1] => A eecomputational agent is considered intel ...

Prevent refreshing the page when submitting information

Whenever I try to post data to PHP, the page ends up reloading. I have attempted to address this issue by following suggestions from similar questions but none of them seem to work as expected. Any assistance is greatly appreciated. <!--HTML--> < ...

Troubleshooting a Node.js Application Deployment Issue on Heroku

2017-09-03T18:50:57.000000+00:00 app[api]: Build initiated by user [me] 2017-09-03T18:51:28.776809+00:00 heroku[web.1]: State transitioned from crashed to starting 2017-09-03T18:51:28.572116+00:00 app[api]: Deploy 20b0544e by user [me] 2017-09-03T18:51: ...

Tips for concurrent playback of audio tracks on an HTML5 video player

Is there a way to add a language changing button for an MKV file with multiple audio tracks? I am looking for some assistance with this task. HTML: <video autoplay id="videoid" controls controlsList="nodownload" disablePictureInPicture poster="<?ph ...

Dynamically adjusting the background color of table elements using JavaScript

Snippet code copied from this link In my app, clicking on the Add New Item button dynamically adds rows. Clicking on any number in the table populates it in the corresponding row. Hovering over the 1st row changes its background color to green along with ...

Troubleshooting Nested Arrays in JavaScript

I have been receiving API JSON data in a specific format and am currently working on reorganizing it. The goal is to group the data first by the start_date and then by the phys_id. The aim is to showcase the available appointment dates followed by each pro ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

combine array elements with corresponding timestamps

I am working with an array of objects that contain timestamps, as shown below. While I have no issues rendering it in React, I am struggling to figure out how to group and sort the data effectively. const data = [ { id: 0, timeStamp: 1619627889000, title: ...

Unleashing the Power of RxJS with OR Conditions

I am working with two Observables. For instance, I am waiting for either an HTTP POST call or a WebSocket call to return so that I can proceed. Once either call returns, I need to verify the information until a certain condition is met. In the following e ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...