Combining objects in an array by a specific property

In my current project, I am working with an array of objects. Each object in this array contains both an amount and a value property. What I need to achieve is that if two or more objects have the same amount value, I want to combine their values into one object.

For clarity, here is an example array:

const array = [
  {
    "key": 1,
    "amount": 11,
    "value": "were"
  },
  {
    "key": 2,
    "amount": 6,
    "value": "locomotives"
  },
  {
    "key": 3,
    "amount": 5,
    "value": "They"
  },
  {
    "key": 4,
    "amount": 5,
    "value": "with"
  },
  {
    "key": 5,
    "amount": 4,
    "value": "used"
  }
]

The desired transformation would look like this:

const array = [
  {
    "key": 1,
    "amount": 11,
    "value": "were"
  },
  {
    "key": 2,
    "amount": 6,
    "value": "locomotives"
  },
  {
    "key": 3,
    "amount": 5,
    "value": "They, width"
  },
  {
    "key": 5,
    "amount": 4,
    "value": "used"
  }
]

I have attempted using methods like reduce and map, but I have encountered difficulties in properly joining the values together.

Answer №1

You may want to consider using the .reduce() method in this scenario:

const array = [
  {
    "key": 1,
    "amount": 11,
    "value": "were"
  },
  {
    "key": 2,
    "amount": 6,
    "value": "locomotives"
  },
  {
    "key": 3,
    "amount": 5,
    "value": "They"
  },
  {
    "key": 4,
    "amount": 5,
    "value": "with"
  },
  {
    "key": 6,
    "amount": 4,
    "value": "used"
  }
];

const result = array.reduce((a, c) => {
  const found = a.find(e => e.amount === c.amount);  
  if (found) found.value = `${found.value}, ${c.value}`;
  return found ? a : a.concat(c);
}, []);

console.log(result);

I trust that this solution will be beneficial to you!

Answer №2

To leverage the power of ES6 Maps along with the .reduce() method in JavaScript, you can structure your data to index by the amount value. By checking if an object's amount value is already present within the Map, you can update its corresponding value accordingly. If the amount value is not found in the Map, simply add it as a new key along with the current object as the value. Finally, utilize Array.from() to obtain an array containing the values of objects returned by the iterator generated from .values()

const array = [ { "key": 1, "amount": 11, "value": "were" }, { "key": 2, "amount": 6, "value": "locomotives" }, { "key": 3, "amount": 5, "value": "They" }, { "key": 4, "amount": 5, "value": "with" }, { "key": 5, "amount": 4, "value": "used" } ];

const res = Array.from(array.reduce((m, o) => {
    const curr = m.get(o.amount);
    return m.set(o.amount, curr && {...curr, value: `${curr.value}, ${o.value}`} || o);
}, new Map).values());
console.log(res);

Answer №3

Personal collection.

let numbers = 
      [ { id: 1, quantity: 3, item: "apples"       } 
      , { id: 2, quantity:  8, item: "bananas"    } 
      , { id: 3, quantity:  4, item: "oranges"    } 
      , { id: 4, quantity:  6, item: "grapes"     } 
      , { id: 5, quantity:  2, item: "kiwis"         } 
      ] 


const updatedNumbers = numbers.reduce((acc,item)=>
                {
                let foundItem = acc.find(e=>e.quantity===item.quantity)
                if (foundItem) foundItem.item += ', '+item.item
                else acc.push(item)
                return acc
                },[])

console.log( updatedNumbers )

Answer №4

Whenever the reduce method is executed, it checks if a value has already been added and then adds the new value:

const result = array.reduce((a, c) => {
  a[c.amount] = a[c.amount] || c;
  if ((Object.keys(a).includes(c.amount.toString())) && (a[c.amount].value!= c.value))
      a[c.amount].value += ', ' + c.value;
  return a;
}, {});

Here's an illustration:

const array = [
  {
    "key": 1,
    "amount": 11,
    "value": "were"
  },
  {
    "key": 2,
    "amount": 6,
    "value": "locomotives"
  },
  {
    "key": 3,
    "amount": 5,
    "value": "They"
  },
  {
    "key": 4,
    "amount": 5,
    "value": "with"
  },
  {
    "key": 5,
    "amount": 4,
    "value": "used"
  }
];

const result = array.reduce((a, c) => {
  a[c.amount] = a[c.amount] || c;
  if ((Object.keys(a).includes(c.amount.toString())) && (a[c.amount].value!= c.value))
      a[c.amount].value += ', ' + c.value;
  return a;
}, {});

console.log(result);

Answer №5

Implement a forEach loop to create an object. If the key named amount already exists, combine the value strings.

const updateData = items => {
  const result = {};
  items.forEach(item => {
    result[item.amount] =
      item.amount in result
        ? {
            ...result[item.amount],
            value: `${result[item.amount].value}, ${item.value}`
          }
        : { ...item };
  });
  return Object.values(result);
};

const dataArr = [
  {
    key: 1,
    amount: 11,
    value: "were"
  },
  {
    key: 2,
    amount: 6,
    value: "locomotives"
  },
  {
    key: 3,
    amount: 5,
    value: "They"
  },
  {
    key: 4,
    amount: 5,
    value: "with"
  },
  {
    key: 5,
    amount: 4,
    value: "used"
  }
];

console.log(updateData(dataArr));

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

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

Tips for escaping an infinite loop within the componentDidUpdate function in reactjs

Currently, I am working on creating dashboards using reactjs. I have successfully implemented 4 tabs or buttons for charts, but I am facing an issue when clicking on different dashboards that have the same chart in the same panel. The chart is not updating ...

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 ...

Exploring the Depths of a Room in ThreeJS

I am currently working on creating a room in ThreeJS, and here is the progress I have made so far: http://jsfiddle.net/7oyq4yqz/ var camera, scene, renderer, geometry, material, mesh, focus; init(); animate(); function init() { scene = new THREE.S ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

How to prevent checkbox autocomplete from selecting the previously checked value using Jquery Ajax

Working on implementing the "Autocomplete ajax search" feature using Php. Successfully fetching data from the database. Currently, when searching for something, the results with checkboxes are displayed. However, when I search for a text, check a checkbo ...

The submit button remains disabled despite completing all required fields

https://jsfiddle.net/xrxjoaqe/ I'm encountering an issue with the bootstrap inline validation files. Despite filling in all the required fields, the submit button remains disabled. $('#registerbutton').attr('disabled', 'di ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

Change the destination of an iFrame upon user click

Is it possible to redirect an iFrame to a different HTML page when clicked by the user? I have an iFrame that is essentially an HTML page. When I click on the iFrame, I want it to take me to another HTML page. This is my code: h1 { ...

What is the method of utilizing shared services when the controllers do not rely on any shared services?

Let's imagine a scenario where there is a module containing only one factory, which serves as the shared service. angular.module('sharedService', []) .factory('sharedSrv', sharedService) function sharedService() { var numbe ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

Send location data to the PHP server through AJAX and then fetch it in JavaScript once it has been handled

I am looking to transfer coordinates from client-side JavaScript to server-side PHP using Ajax, and then retrieve the processed result back to JavaScript for further use. While I have managed to pass the data to PHP successfully, I am struggling to figure ...

Most effective method to verify the alignment of indices between two arrays

I am currently working with a .txt file that has been scanned into two arrays: departures[236] and arrivals[236]. In my code, I have implemented a function to compare two user inputs, depart_input and arrive_input. However, instead of returning the corre ...

How to feed images to Angular's UI Bootstrap Carousel

In my current project, I am incorporating the Angular UI Bootstrap carousel and want to customize it by using my own images. Below is the code snippet for the Carousel Controller that I have implemented: .controller('CarouselCtrl', function ($sc ...

What is the best way to align text extracted from an API using JavaScript?

I'm currently exploring content generation through APIs, but I'm facing an issue where the text generated is not aligning properly within the container on the screen. The main problem lies in getting the card to be centered on the screen with al ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Fill an array with the column indexes that match a specific set of strings

My goal is to fill a 2-Dimensional Variant Array with a group of strings and their corresponding column numbers (Positions) from different worksheets. To achieve this, I have created an intermediate procedure that transfers the values from each worksheet ...

What is the point of utilizing angular.extend in this situation?

After inheriting a codebase, I stumbled upon the following code snippet (with some parameters simplified and anonymized): /** * @param {float} num1 * @param {string} str1 * @param {string} str2 * @param {boolean} flag & @return (object) */ sr ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

Error in JavaScript: addition of all numbers not functioning properly within a loop

After attempting to sum all the numeric values within the result[i].quantity array using += or dataset.quantity = 0 + Number(result[i].quantity);, I encountered issues where the console.log was returning either NaN or the value from the last iteration like ...