Combine elements in an array based on their values and calculate the occurrences of each

Here is an array of objects that needs to be combined based on the item value:

myArray = [
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  }
]

The desired result should look like this:

var myResultArray = [
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
    count: 4
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
    count: 3
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
    count: 2
  },
]

How can we achieve this? Consider using Lodash's _.groupBy() function to group by the item key:

var myGrouped = _.groupBy(myArray, 'item');

However, further steps are needed to obtain the final result. Many users suggest using _.reduce() or _.map(). If you attempt to combine _.groupBy() with _.map(), ensure proper implementation for successful execution.

Thank you.

Answer №1

Using _.groupBy in combination with _.map offers a straightforward solution. To create an appropriate callback function for the _.map, consider the following:

function (elements) {
  elements[0].quantity = elements.length;
  return elements[0];
}

You could also streamline this process further using ES6 arrow functions.

const listArray = [{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 2","material":"Material2","type":"shell"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 2","material":"Material2","type":"shell"},{"item":"Item 3","material":"Material3","type":"support"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 3","material":"Material3","type":"support"},{"item":"Item 2","material":"Material2","type":"shell"}];

const updatedListArray =
  _(listArray)
    .groupBy('item')
    .map(elements => (elements[0].quantity = elements.length, elements[0]))
    .value();

console.log(updatedListArray);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

Answer №2

After exploring my options, I decided to implement the following solution:

const organizedData = [];
_(originalData).group('element').each(function(val, k) {
  const dataObj = {};  
  dataObj.totalCount = val.length;
  dataObj.category = val[0].category;
  dataObj.info = val[0].info;
  dataObj.desc = k;
  organizedData.push(dataObj);
});                 

Answer №3

To accomplish this task without relying on Lodash, you can achieve the desired array by using the following approach:

const result = myArray.reduce((accumulator, value) => {
  let summary = accumulator.get(value.item) || Object.assign({}, value, {quantity: 0});
  summary.quantity++;
  return accumulator.set(value.item, summary);
}, new Map());

console.log([...result.values()]);

Answer №4

Utilizing the powerful combination of _.countBy and _.uniqBy functions

let result = _.chain(myArray)
    .countBy('item') // retrieves count of each item
    .thru(counts => // counts = {Item 1: 4, Item 2: 3, Item 3: 2}
        _.chain(myArray)
            .uniqBy('item') // obtains unique items
            .map(item =>  // assigns count to each unique item
                _.assign(
                    item, 
                    {count: counts[item.item]}
                );
            )
            .value();
    )
    .value();

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

I'm having an issue with my progress bar in ReactJS - it seems to move when I scroll the window instead of

My code includes a progress bar that works fine - it shows a movable progress bar when the window is scrolled. However, I want the progress bar to move when scrolling inside my div, not on the entire window. I am currently using jQuery for this functionali ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

Learn the process of pulling information from mongoose and incorporating it into all pages

I am currently developing a basic website where users need to register and subscribe to activated challenges. I am utilizing passport for user registration, login forms, and saving user email and password in the database. However, I am facing an issue when ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Ways to showcase a numeric value retrieved from an API on my webpage?

Greetings, esteemed guest! You are visitor number <span id=VisitorCounter></span> <script> fetch("https://unique-api-source.com/visits/getvisitorcount", { method: "GET", // mode: "cors", headers: { ...

Sorting an array using the Merge Sort algorithm in Python can not only efficiently organize the

I have designed a system that randomly generates numbers for a list or an array. I am trying to calculate the time it takes to sort this list and the number of swaps needed for sorting. Below is the code I have written. While the code successfully sorts t ...

I am concerned about the security of my games as they can be easily hacked through right-click inspect. What measures can

As a newcomer to game development, I am creating web games using JS, HTML, and CSS. However, I have encountered an issue with preventing right-click inspect hacking, which has led to people hacking my games through this method. I am wondering, how can I s ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

What changes can I make to this jquery code to utilize a background image instead of a background color?

Can someone help me modify this snippet to set a background-image instead of changing the background color? <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("#button_layer").hide(); $("#im ...

Vuejs: Users can still access routes even after the token has been deleted

Upon logging out of my application, I have encountered a peculiar issue. Certain inner links, such as those within a user's panel, remain accessible even after I have logged out and deleted a token. However, other links are not. Any suggestions on how ...

Encountering an unexpected token error while using Webpack with React modules

I've been attempting to utilize the react-spin npm package, but when I try to create a bundle.js with webpack, an error occurs: Module parse failed: /Users/nir/browsewidget/node_modules/react-spin/src/main.js Line 29: Unexpected token < You may ne ...

How to choose between GET/POST and USE in ExpressJS for URL filtering

router.get('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) VS router.use('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) Could someon ...

State is not being updated by useState after the second API call in MUI and ReactJS

I encountered an issue while using the Material-UI Autocomplete component for a search box. The problem arises when fetching options from an API and passing them to the component. Initially, the dropdown displays the options correctly. However, upon closin ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

ways to incorporate searching within JSON data using AJAX and jQuery in JavaScript

My search box needs to have JSON data appended into it. Below is the HTML code: <input type="search" id="merchantName" name="merchant" placeholder="enter merchant name"></input> I have JSON data containing merchant names that I want to appen ...

Is it possible to export a constant from within a default function to a different file?

As a newcomer to React and React Native, I am looking to pass a const variable from within a function to another file. I attempted defining it outside of the function and allowing it to be modified inside the function, but encountered an invalid Hook Call ...

checkbox appear based on vue condition

I have checkboxes on my list that are always checked, but I only want them to be checked if the associated object's property "include" is set to true. Currently, all the checkboxes are checked by default, and when I click on them, they uncheck and ex ...

Employing ng-style for establishing background when the value does not align

Greetings all! I am using ng-repeat to create a list of items within a ul element. Within the json data, there is a specific value that I want to highlight if it does not match a predefined string. Here's what I have so far: ng-style="{'backgro ...