Ways to decrease and transform a collection of objects?

What is the best way to condense and transform this object array into a new array?

Here is the data I am working with:

var objArray = 
  [{
    state: 'NY',
    type: 'A',
    population: 100
  },
  {
    state: 'NY',
    type: 'A',
    population: 300
  },
  {
    state: 'NY',
    type: 'B',
    population: 200
  },
  {
    state: 'CA',
    type: 'A',
    population: 400
  },
  {
    state: 'CA',
    type: 'A',
    population: 400
  }];

In cases where an entry shares both the same state AND type, I want to merge them into one entry while adding up their populations.

Finally, I aim to map this condensed data into an array structured like this:

 var outputArray = [ ['A', 'NY', 400 ], ['B', 'NY', 200], ['A', 'CA', 800] ]

Answer №1

To start, the initial step would be to decrease it. This process can be achieved in the following manner...

objArray.reduce((prev, obj) => {
    if(1 + (indx = prev.findIndex(oldObj => oldObj.type === obj.type && oldObj.state === obj.state))) {
        prev[indx].population += obj.population;
    } else {
        prev.push({...obj})
    }
    return prev;
}, [])

This operation manipulates the gathered array by making modifications and returns it within the reduce callback function. It will either adjust an existing value's population if a matching one with the correct state and type is found, or append a new object at the end of the array.

Next, you must proceed to perform mapping on it.

.map(obj => [ obj.type, obj.state, obj.population ])

Answer №2

If you're looking to enhance your Javascript applications, I highly recommend incorporating the lodash package. This widely-used package offers an array of useful functions for array manipulation. Check out this helpful post on using lodash to sum values based on groups. To adapt the code snippet for your specific parameters, simply update the groupBy command as follows:

_.groupBy(objArray, function(val){
    return val.state + "#" + val.type
})

Answer №3

Here is a possible solution:

const newArray = Object.keys(objArray).map(function (key) { return Object.keys(objArray[key]).map(function (key) { return [[objArray[0].country, objArray[0].city, objArray[0].population],[objArray[1].country, objArray[1].city, objArray[1].population]]}); })[0][0];

Answer №4

In the scenario where you are certain that the state and type values will never contain a specific character like '_', you can combine them to create a unique key, similar to a composite key in a database. For instance, you could use 'NY_A' as a composite key. By organizing an object with these unique keys, summing up the populations, and ultimately breaking them down into an array:

Object.entries(
    objArray.reduce((acc,curr) => (
    acc[curr.type + '_' + curr.state] = curr.population + (acc[curr.type + '_' + curr.state] || 0)
    , acc), {}))
.map(item => [...item[0].split('_'), item[1]])

Answer №5

const _ = require('lodash')

const data = [
  { region: 'NY', category: 'A', population: 100 },
  { region: 'NY', category: 'A', population: 300 },
  { region: 'NY', category: 'B', population: 200 },
  { region: 'CA', category: 'A', population: 400 },
  { region: 'CA', category: 'A', population: 400 }
]

const expectedResults = [
  ['A', 'NY', 400],
  ['B', 'NY', 200],
  ['A', 'CA', 800]
]

const calculatedResults = _(data)
  .groupBy(({ region, category }) => [region, category].join(':'))
  .mapValues((regions) => regions.reduce((totalPop, { population }) => totalPop + population, 0))
  .map((populationTotal, regionCategory) => {
    const [region, category] = regionCategory.split(':')
    return [category, region, populationTotal]
  })
  .value()

console.log("Expected Results:")
console.log(expectedResults)
console.log("Calculated Results:")
console.log(calculatedResults)

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

Use ajax calls instead of using the bind() function in Drupal for better performance

Currently, I have an AJAX call that is bound to the window popstate event. While it works fine, the issue arises when parsing arguments from the querystring. The problem lies in the fact that the ajax call gets bound to the window on page load, causing the ...

Tips for passing a "NULL" value into a nullable field when making a call from JavaScript to an ASP.NET WebService

Is there a way to pass the value of "NULL" into a nullable field when calling an ASP.NET WebService from JavaScript? I am currently calling the method in this manner from JavaScript: ws_data.SaveTasks(eval({"MyValue":"null"}), OnSaveComplete, OnError, On ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

A guide on dynamically loading images based on specified conditions in AngularJS

I am trying to display different images based on a value. If the value is greater than 3.50, image1 should be shown; if it is equal to or less than 3.50, image2 should be shown. I have attempted to write this code but I cannot find where I made a mistake. ...

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

Update your Electron application with the npm update command

I have recently published an app on a local npm repository, and this particular app serves as a crucial dependency for my second electron application. The electron app I am working on is structured around node_modules/my-first-app/dist/index.html. I am w ...

JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME. I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below ...

Within the domain of Java programming, input text can be processed and organized into a two-dimensional character array

I am struggling with understanding how to approach solving this problem. I need some resources to guide me through the process or maybe someone who can explain it in a different way that will help me make a start. Alternatively, if anyone could offer a sta ...

Setting up TailwindCSS in Nuxt3: A step-by-step guide

Looking to customize the default font Proxima Nova from TailwindCSS in my Nuxt3 project but navigating the file structure is a bit tricky for me. I've gone ahead and installed the tailwindcss module: npm i -D @nuxtjs/tailwindcss and added the module ...

What is the best way to initiate WebXR from an iframe in a Next.js environment?

I am currently working on a Next.js app: https://codesandbox.io/s/next-js-forked-6fgnr7?file=/index.tsx I have implemented the functionality for it to open WebXR on Android Chrome when clicking on the AR button located at the bottom left ("in AR betracht ...

Executing a jQuery function in vb.net codeBy utilizing vb.net, the jQuery

Encountering an unusual issue where I need to toggle the visibility of a div both server side and client side without being able to change it to a panel. To achieve this, I am currently using the following code to toggle its visibility client side: $(&ap ...

Delete the JSON object stored in local storage and reconstruct the array from scratch

I've encountered an issue with deleting an item from LocalStorage...here's the JSON data stored in LocalStorage. { "1461569942024" : {"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"}, "1461570048166" : {"t_id":1461570048166 ...

Having trouble with the Post Request feature as an error message pops up saying "unable to post /addstudent/add"

I'm encountering an issue with the post request I'm trying to send. I've attempted to work on it both in Postman and with forms, but I keep getting an error that says "cannot POST /addstudent/add". Below you'll find the code snippets fo ...

Setting up an Express route with dynamic parameters in Node.js

I am in the process of creating a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I'm working on setting up an Express route that will retrieve specific data from MongoDB based on the provided ID. Here is the current code snippet for the ro ...

Combining JSON objects within an array

I'm working with a JSON Array that looks like this: [ {"Name" : "Arrow", "Year" : "2001" }, {"Name" : "Arrow", "Type" : "Action-Drama" }, { "Name" : "GOT", "Type" : "Action-Drama" } ] and I want to convert it to look like this: [ { "Name" : ...

Exploring the Intersection of jQuery and Rails in Dynamic Form Development

I am currently working on an interactive form for a Rails project and need some assistance with listing multiple jQuery functions in the same file. Whenever I try to add a second set of code language, it seems to break the entire file. Below is the Rails ...

What is the best way to incorporate JavaScript code as React syntax?

For my project, I am using the OpenLayers API Map. I'm unsure of the correct way to incorporate JavaScript code in React or vice versa. Here is an answer on how to use markers in the map, but I am struggling to implement it in my current code since I ...

Include a hyperlink that is activated when hovering over an image

UPDATE: I am amazed by the quick responses, this is my first time using this platform. Thank you to everyone who helped out. The person who provided the answer understood exactly what I was looking for. To others who responded, thank you as well. I need h ...