Utilizing underscores to assign values as keys in a minimized object

After some tinkering, I successfully streamlined my Price Amount Object by combining it like so:

stooges = [{Price: 1.2, Amount: 40}, {Price: 1.3, Amount: 50}, {Price: 1.2, Amount: 60}];

inputarray = _.map  _.groupBy(stooges, 'Price'), (v, k) -> 
        {  Price: k
        Amount : _.reduce(v, ((m, i) -> m + i['Amount']), 0)}

console.log(inputarray)

This code generates the following output:

[Object { Price="1.2", Amount=100}, Object { Price="1.3", Amount=50}]

Although I feel the grouping might be excessive, I aim to achieve a structure similar to this:

[ { 1.2 : 100 } , { 1.3 : 50 } ]

Where the Price serves as the Key and the Amount acts as the Value. Struggling a bit with this one.

Answer №1

Here is a suggested solution:

_.map(_.groupBy(stooges, 'Price'), function(v, k){
  var obj = {};
  obj[k] = _.reduce(v, function(m, i){ return m + i['Amount'] }, 0);
  return obj;
})

The output of the code above is as follows:

[{ "1.2": 100 }, { "1.3": 50 }]

Note: Instead of returning an array, you can use this alternative approach with Lo-Dash (recommended over Underscore) to get a single object with all prices as keys and the total amount as values:

_(stooges).groupBy('Price').mapValues(function(stooge){
  return _(stooge).pluck('Amount').reduce(function(total, amount){
    return total + amount;
  })
}).value()

With this method, the result will be:

{ "1.2": 100, "1.3": 50 }

Answer №2

outcome1 = _.pluck somearray,'Value'

outcome2 = _.pluck somearray,'Quantity'

awesome = _.object(outcome1,outcome2);

Thank you, I understand now but it's not as sophisticated as yours!

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

AngularJS click directives and Google Chrome's content protection policy

Here is an interesting scenario I encountered recently. The new Google Chrome's Content Security Policy now prohibits the use of inline scripts or event handlers like onclick or ontouch within the HTML itself. This means that we are required to write ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

Traversing the nested arrays, processing column by column

Below is an array of subarrays const array = [ [0, 1, 2, 3], // Going from top to bottom? [4, 5, 6, 7, 8, 9], // | [10, 11, 12, 13, 14], // | [15, 16, 17, 18, 19], // | ] // V My goal is to achieve the fol ...

Guide to positioning a THREE.js plane onto the exterior of a spherical object

Just starting out with Threejs and 3D graphics. I'm interested in learning how to position a plane of any dimensions on the surface of a sphere. Here's an example image of what I'm aiming for: example image ...

The intricacy of the jQuery each function and its interaction with $(this

EXPLANATION: I am working with two elements, each containing a set of options. The first element has options with db-ids as values, acting as parent categories. The second element is filled with options where the parent db-ids are their values and their o ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

I'm encountering an issue with Material-ui Tabs where clicking submit to go to the next page results in the tab being removed. Does anyone know

I'm facing an issue with my tabs setup. When I click submit, it takes me to the correct page but also removes the tab. How can I prevent this from happening? To better illustrate the problem, I have recreated it in CodeSandbox: https://codesandbox.io ...

Localstorage functionality in Angular 2

I'm currently exploring the usage of localstorage in angular 2 while utilizing angular cli. app.component.ts export class AppComponent implements OnInit { currentItem: string; newTodo: string; todos: any; constructor(){ this ...

Customize the Color of the Selected Button on the Menu (Implementing Ant Design Components in React)

Hello, I am reaching out to inquire about the process of updating the menu associated with a specific button in Ant Design using React. I am interested in changing the options that are displayed when the button is clicked. I would greatly appreciate any g ...

How to Extract Calendar Week Numbers in React from a Specific Month

Is there anyone who can assist me in calculating the week numbers for a specific month? For instance, July is expected to have week numbers 26, 27, 28, 29, and 30. How can I accomplish this task and store the results in an array? Currently, I am only abl ...

How to retrieve user data based on ID using Angular SDK

I have limited experience with the Angular SDK and lb-service, and I'm unsure about how to retrieve another user's information by their ID within a controller. I am trying to implement a feature for displaying a friend list, where each user only ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

Do the incoming ajax data trigger any "if" conditionals?

Very new to coding, so forgive me if this is a simple question... I'm currently developing a web application where clicking a "Search" button triggers an ajax request to fetch data, which is then used to populate a table using the jQuery .DataTable m ...

What is the best way to retrieve the identity or specifics of the item that was right-clicked within the context menu

My AngularJS populated table includes a link button. When I right-click on this button, I've created a specific context menu using jQuery that pops up. The issue arises when I try to retrieve the ID of the item I clicked on in the context menu (such a ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

Identifying the Ajax request URL

I am working on a project where I have an HTML document that retrieves content from a PHP file using an AJAX call. The key portion of my code can be seen below: default.html : /*more code above*/ var PHP_URL = "content.php"; var Content = document.getEle ...

Are Nodes Distributed and Styled in Polymer's Network?

Let's imagine I have created two unique custom elements as extensions of the innovative Polymer Element: c-el1 c-el2 Here is how they are templated: c-el1 <dom-module id="c-el1"> <template> <style> p{ ...