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 :: upgrade or update nodejs 
Javascript :: using template literals to create html 
Javascript :: what is react 
Javascript :: js date in arabic 
Javascript :: vuejs v-model select 
Javascript :: js loop through function arguments 
Javascript :: reactstrap dropdown 
Javascript :: cancel an event in javascript 
Javascript :: react leaflet disable zoom 
Javascript :: date.gettime is not a function 
Javascript :: How to Use the trim() String Method in javascript 
Javascript :: find remainder in javascript 
Javascript :: add background image react native 
Javascript :: Convert array to string while preserving brackets 
Javascript :: javascript template string 
Javascript :: expressjs req.body.parameters 
Javascript :: how to push two values in array at once 
Javascript :: dynamic set required in angular using formcontrol 
Javascript :: how to format datetime in javascript 
Javascript :: compare between two arrays javascript 
Javascript :: node js documentation 
Javascript :: get the location of an item in an array 
Javascript :: sum 2d array javascript 
Javascript :: what is a promise 
Javascript :: using fb login with angular app 
Javascript :: nodejs add element to array 
Javascript :: react cors error 
Javascript :: string theory 
Javascript :: js fetch status of 500 
Javascript :: react js docker 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =