Organize the main array by subgroup values and merge corresponding fields

I am having difficulty grouping an array with its sub-array. Here is the original array I am working with:

var people = [
  {
    name: "Bob",
    age: "20",
    car: {
      colour: "Blue",
      size: "Big",
      rpm: "380"
    }
  },
  {
    name: "Mary",
    age: "21",
    car: {
      colour: "Orange",
      size: "Small",
      rpm: "20"
    }
  },
  {
    name: "Janet",
    age: "22",
    car: {
      colour: "Blue",
      size: "Big",
      rpm: "380"
    }
  }
];

My goal is to group the data by the color of the car object in this specific format:

var cars = [
  {
    colour: "Blue",
    size: "Big",
    rpm: "380",
    people: [{ name: "Bob", age: "20" }, { name: "Janet", age: "22" }]
  },
  {
    colour: "Orange",
    size: "Small",
    rpm: "20",
    people: [{ name: "Mary", age: "21" }]
  }
];

As a newcomer to JavaScript, any assistance or suggestions you can offer would be greatly appreciated. I am open to using external libraries if necessary.

EDIT In response to @ths, I managed to extract the car object into the main array successfully using the following code:

resultArray = [];

people.forEach(function(people) {
    let carObj = people.car;
    console.log("TCL: carObj", carObj)
    carObj["people"] = people;
    resultArray.push(carObj);
  });

However, I encountered difficulties when trying to merge the arrays based on different car types.

Answer №1

var people = [
  {
    name: "Bob",
    age: "20",
    car: {
      colour: "Blue",
      size: "Big",
      rpm: "380"
    }
  },
  {
    name: "Mary",
    age: "21",
    car: {
      colour: "Orange",
      size: "Small",
      rpm: "20"
    }
  },
  {
    name: "Janet",
    age: "22",
    car: {
      colour: "Blue",
      size: "Big",
      rpm: "380"
    }
  }
];

let carMap = {};

people.forEach(p => {
  const carKey = `${p.car.colour}-${p.car.size}-${p.car.rpm}`;
  
  if (carKey in carMap) {
    carMap[carKey].people.push({
      name: p.name,
      age: p.age
    });
  } else {
    carMap[carKey] = {
      ...p.car,
      people: [{
        name: p.name,
        age: p.age
      }]
    };
  }
})

console.log(Object.values(carMap));

Create a mapping of cars to people by combining the attributes of each car. Retrieve the values of the carMap at the end.

Answer №2

Utilizing the .reduce technique offers a way to restructure arrays into objects containing arrays with a modified format:

  var people = [
        {
            name: "Bob",
            age: "20",
            car: {
                colour: "Blue",
                size: "Big",
                rpm: "380"
            }
        },
        {
            name: "Mary",
            age: "21",
            car: {
                colour: "Orange",
                size: "Small",
                rpm: "20"
            }
        },
        {
            name: "Janet",
            age: "22",
            car: {
                colour: "Blue",
                size: "Big",
                rpm: "380"
            }
        }
    ];

    const generateId = (object) => Object.keys(object).map(key => key + object[key]).join('-');

    var personByCar = Object.values(people.reduce((acc, person) => {
        // Uniquely identify the car properties:
        const carId = generateId(person.car);
        // Append the people property to contain relevant persons
        if(!acc.hasOwnProperty(carId)){
            acc[carId] = {...person.car, people: []};
        }
        // Include the person
        acc[carId].people.push({person});
        return acc;
    }, {}));

    console.log(personByCar)

For further details on reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

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

Creating a lineup of products

I'm currently developing a Spritekit game for iOS7, and I want to incorporate a feature where coins fall down the screen from top to bottom in a continuous manner. While I understand that using an array is the preferred method for managing a series of ...

The child_process module has yet to be loaded

Exploring NodeJS to execute a PowerShell script from JavaScript. Found this code snippet online: var spawn = require("child_process").spawn, child; child = spawn("powershell.exe",["c:\\test\\mypstest.ps1 -arg1 1"]); child.stdout.on(" ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

What is the process for transferring multiple files using a read stream in Node.js?

Suppose I have a folder containing two files, index.html and style.css, and I would like to send both of them. How can I achieve this with Node.js? Router.get('/', function(req, res) { var indexStream = fs.createWriteStream('path to index ...

Saving additional user information within the users' data

I'm considering a method that might be questionable. I'm thinking of storing a user's likes under the profile attribute in my user object. Here's an example of what it would look like: user = { ... profile: { likes: [ { ...

The useState function does not trigger a re-render

I'm currently facing an issue with the useState hook where the state gets updated, but the changes are not reflected until I manually refresh the app. To provide some context, I initialize an array called sampleFriends containing objects with fields " ...

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Finding the maximum number of elements in an array using PHP

There is a collection of cities in an array: Array ( [0] => Delhi [1] => Delhi [2] => Delhi [3] => Delhi [4] => Delhi [5] => Delhi [6] => Beng ...

What is the best way to turn off ajax functionality when detecting IE8?

Encountering a significant problem where every time the save/cancel button is clicked, IE8 freezes (while Firefox and Chrome work without issue). When JavaScript is disabled in the browser, it works correctly. There is a suspicion that an ajax call linke ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

Tips on setting a value to zero in Angular when there is no input

Is there a way to organize the data and show the PRN entries based on the date, for instance, when the month is January? If there is data for machine 1 with assetCode: PRN, it should be displayed under the header for children. Similarly, if there is data f ...

What is the best way to condense a touchmove event listener in JavaScript?

Trickshot #29 demonstrates how touch events can be defined in jQuery. I have reinterpreted it with my own unique style of coding in this fiddle. The author sets up a touchmove listener every time a touchstart event is triggered. request.dom.ball.on(&apos ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

When the enter key is pressed, shift the text to a different input field

I am facing a complex requirement How can I detect the pressing of the ENTER key within a text box with the following conditions: If the cursor is at the end of a sentence, it should create a new text box on the next row. If the cursor is in the middle ...

outputting random selections from an array

I've been working on a function that selects random numbers from a specified array and displays them to the standard output. These chosen numbers must not repeat, and the number of selections is provided as an argument to the function along with the a ...

The baguetteBox.js malfunctioning issue is causing the controls to appear at the bottom of the page

I have integrated baguetteBox.js into a website with two separate pages: homepage gallery On the gallery page, everything is working perfectly fine. However, on the homepage, I am facing an issue where the lightbox controls (e.g., id="baguetteBox-overla ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...