Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Group an Array By an Object Property, array, object

const groupBy = (arr, groupFn) =>
  arr.reduce(
    (grouped, obj) => ({
      ...grouped,
      [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj],
    }),
    {}
  );
const people = [
  { name: 'Matt' },
  { name: 'Sam' },
  { name: 'John' },
  { name: 'Mac' },
];
const groupedByNameLength = groupBy(people, (person) => person.name.length);
/**
{
  '3': [ { name: 'Sam' }, { name: 'Mac' } ],
  '4': [ { name: 'Matt' }, { name: 'John' } ]
}
 */
console.log(groupedByNameLength);
Comment

how to group an array of objects

const groupBy = (array, key) => {
  // Return the end result
  return array.reduce((result, currentValue) => {
    // If an array already present for key, push it to the array. Else create an array and push the object
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue
    );
    // Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
    return result;
  }, {}); // empty object is the initial value for result object
};
Comment

PREVIOUS NEXT
Code Example
Javascript :: nodejs put array in file 
Javascript :: javascript search in array of strings 
Javascript :: is array equal javascript 
Javascript :: reference body js 
Javascript :: react map array limit 
Javascript :: javascript button go to url 
Javascript :: dom key event shift is pressed 
Javascript :: jquery nth child 
Javascript :: create array number javascript 
Javascript :: discord.js change bot status 
Javascript :: javascript includes case insensitive 
Javascript :: converting bytes into kb js 
Javascript :: scroll to top jquery 
Javascript :: how to find the key of an value in an object 
Javascript :: module not found reactstrap 
Javascript :: Check if a JavaScript string is a URL 
Javascript :: vh not working on phone 
Javascript :: click a link using jquery 
Javascript :: query params vuejs 
Javascript :: translatex in javascript 
Javascript :: npm view available versions 
Javascript :: react-native loading screen 
Javascript :: disable option dropdown jquery 
Javascript :: jquery each data 
Javascript :: box shadow javascript style change 
Javascript :: js promise all return json array 
Javascript :: jvascript number to column letter 
Javascript :: enzyme check state 
Javascript :: laravel variable in javascript 
Javascript :: js mouse enter 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =