You codes are a little close to the goal, just need to adjust something.

Please see the comment in below demo:

  1. When acc.find doesn't find anything, then push one element {name:d.name, data: [value]}

  2. if found, then push one {value: ...} into data property.

const arr = [
  {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
  {name: "survey with select", value: "survey with select answer", count: 2},
  {name: "werasd", value: "Donald", count: 1},
  {name: "werasd", value: "Jim", count: 1}
];

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.name);
  //const value = { name: d.name, val: d.value };
  const value = { value: d.value, count: d.count }; // the element in data property
  if (!found) {
    //acc.push(...value);
    acc.push({name:d.name, data: [value]}) // not found, so need to add data property
  }
  else {
    //acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
    found.data.push(value) // if found, that means data property exists, so just push new element to found.data.
  }
  return acc;
}, []);

console.log(result)

Answer from Sphinx on Stack Overflow
Top answer
1 of 5
24

You codes are a little close to the goal, just need to adjust something.

Please see the comment in below demo:

  1. When acc.find doesn't find anything, then push one element {name:d.name, data: [value]}

  2. if found, then push one {value: ...} into data property.

const arr = [
  {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
  {name: "survey with select", value: "survey with select answer", count: 2},
  {name: "werasd", value: "Donald", count: 1},
  {name: "werasd", value: "Jim", count: 1}
];

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.name);
  //const value = { name: d.name, val: d.value };
  const value = { value: d.value, count: d.count }; // the element in data property
  if (!found) {
    //acc.push(...value);
    acc.push({name:d.name, data: [value]}) // not found, so need to add data property
  }
  else {
    //acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
    found.data.push(value) // if found, that means data property exists, so just push new element to found.data.
  }
  return acc;
}, []);

console.log(result)

2 of 5
2

You're not far off. This would be a simple change to two lines of your code to achieve it:

const arr = [
  {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
  {name: "survey with select", value: "survey with select answer", count: 2},
  {name: "werasd", value: "Donald", count: 1},
  {name: "werasd", value: "Jim", count: 1}
];

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.name);
  const value = { name: d.name, val: d.value };
  if (found) {
    found.data.push(value);
  }
  else {
    acc.push({ name: d.name, data: [{ value: d.value, count: d.count }] });
  }
  return acc;
}, []);

console.log(result)

Here are the differences:

-     acc.push(...value);
+     found.data.push(value);


-    acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
+    acc.push({ name: d.name, data: [{ value: d.value, count: d.count }] });
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript reduce array of objects by key | example code
JavaScript reduce array of objects by key | Example code
April 25, 2023 - Use reduce() method with findIndex() method to reduce array of objects by key in JavaScript. Simple example code Reduce array of objects
🌐
Redbitdev
redbitdev.com › post › using-array-reduce-with-objects
Using Array.reduce With Objects
September 21, 2021 - Example 5 reduces the keys from the 'person' object into a new object that only contains the properties whose keys are _not_ included in the 'disallowedProperties' array. If you add a new property to the 'person' object it _will_ appear in the result unless you also add the property name to the disallowed properties.
🌐
Stephan Miller
stephanmiller.com › javascript-reduce
JavaScript Reduce - A Complete Guide to the Only JS Array Function You Really Need — Stephan Miller
January 11, 2024 - The reduce method iterates over each object in the products array, continuously accumulating the total cost. What? Yes, I know reduce is for arrays, but Object.keys() returns an array of the keys in an object.
🌐
GitHub
gist.github.com › alexpetergill › b2080174d9ecee70755718f43c9d664f
JavaScript - Reduce Array of Objects by Key · GitHub
JavaScript - Reduce Array of Objects by Key · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
How to reduce array of objects to array - JavaScript - The freeCodeCamp Forum
June 12, 2022 - Greetings, Say for example i dont wish to use a for loop or forEach, I also dont wish to map and then do another pass to clear undefined values. how would I say convert an array of objects into different array, want this input: [ {a:1}, {name: 'Jane'}, {}, {b:2}, {name: 'Smith'}, {name: 'Fatima'}, ] to output e.g. : ['Jane', 'Smith', 'Fatima'] Can it be done using reduce?
🌐
Simplilearn
simplilearn.com › home › resources › software development › javascript tutorial: learn javascript from scratch › javascript array reduce(): explained with syntax and examples
JavaScript Array Reduce(): Explained With Syntax and Examples | Simplilearn
July 16, 2024 - Learn everything about JavaScript array reduce and how you can use this method to reduce an array to a single value. Explained with syntax and examples.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Amit Merchant
amitmerchant.com › reduce-array-of-objects-to-an-object-in-javascript
Reduce array of objects to an object in JavaScript
May 17, 2022 - To achieve this, I used the Array.reduce() method like so. const ethnicitiesObject = ethnicities.reduce( (previousObject, currentObject) => { return Object.assign(previousObject, { [currentObject.id]: currentObject.name }) }, {}); ...
Find elsewhere
🌐
The New Stack
thenewstack.io › home › javascript: build objects and eliminate looping with reduce()
JavaScript: Build Objects and Eliminate Looping with Reduce() - The New Stack
September 3, 2022 - The baseline reducer function will look like this: If we want to turn the fruit array of objects in this example into one single object, it will look like this in its long form. There is a way to make this shorter. This is the syntactical sugar version of this. And it looks like this. The example above is making a copy of the previous accumulator and adding the current value’s key/value pair into it.
Top answer
1 of 1
1

I think it's best to think of the problem as 2 different steps:

  • First, get all things that belong to the same date together. This is a groupBy that you should be able to look up on StackOverflow or borrow from an existing library.
  • Then, you merge each of the date groups in to a single object.

The merge operation is a bit more custom than the groupBy operation. You can implement it in many ways. I would propose to:

  • Implement merge to deal with just 2 objects
  • Inside merge, loop over all unique keys in those objects and sum them (excluding the date key)
  • To apply merge to a date group, use reduce. Note that it's safe to not provide a seed argument here, because you are guaranteed to not have empty groups.

Copy// Merge two date-service entries in to one
const merge = (a, b) => {
  const merged = Object.assign({}, a);
  
  Object.keys(b).forEach(k => {
    if (k !== "date")
      merged[k] = (merged[k] || 0) + b[k];
  });
  
  return merged;
};

const input = [ { date: "3/12/2022", oService: 10},
                { date: "3/13/2022", oService: 12, aService: 1},
                { date: "3/13/2022", oService: 1 }];
          
// Create groups that have a matching date
const byDate = groupByProp("date", input);

// Reduce each group to a single item by merging
const all = Object.values(byDate).map(xs => xs.reduce(merge));

console.log(all);

// A basic `groupBy` implementation
function groupByProp(prop, xs) { 
  return xs.reduce(
    (groups, x) => {
      const k = x[prop];
      if (!groups[k]) groups[k] = [x];
      else groups[k].push(x);
      return groups;
    },
    {}
  );
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
24ways
24ways.org › 2019 › five-interesting-ways-to-use-array-reduce
Five Interesting Ways to Use Array.reduce() (And One Boring Way) ◆ 24 ways
Inside the Array.reduce() callback function, we’ll check to see if the criteria is a function, or a property of the item. Then we’ll get its value from the current item. If there’s no property in the obj with that value yet, we’ll create ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript - MDN Web Docs
The reduce() method is generic. It only expects the this value to have a length property and integer-keyed properties. If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned ...
🌐
GitHub
gist.github.com › estliberitas › b9ddb1a491acf40f1714
Object to Array using Object.keys and Array#reduce · GitHub
December 5, 2018 - Object to Array using Object.keys and Array#reduce - object-to-array.js
🌐
W3Schools
w3schools.com › jsref › jsref_reduce.asp
JavaScript Array reduce() Method
at() byteLength byteOffset bytesPerElement copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() forEach() from() includes() indexOf() join() keys() lastIndexOf() length map() name of() reduce() reduceRight() reverse() set() slice() some() sort() subarray() toLocaleString() toReversed() toSorted() toString() values() with() Temporal Objects New Temporal.Duration ·
🌐
Rip Tutorial
riptutorial.com › reducing values
JavaScript Tutorial => Reducing values - Arrays
array.reduce((obj, current) => Object.assign(obj, { [current.key]: current.value }), {}); 7 · array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {}); Note that the Rest/Spread Properties is not in the list of finished ...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-array-into-array-of-objects-using-map-reduce-in-javascript
How to Convert Array into Array of Objects using map() & reduce() in JavaScript? | GeeksforGeeks
May 7, 2024 - Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
🌐
DEV Community
dev.to › sanspanic › the-javascript-reduce-method-3j8l
The JavaScript Reduce Method - DEV Community
July 23, 2021 - The current value, named current object here, is the first object in the original array. The reducer function initialises a new variable, newAcc. newAcc is an object, with the spread of the current (still empty) accumulator. We assign a new property to newAcc, with the key being the current object's id, and the value being an object with the bad and good outcomes arrays.