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 :: setup ejs views directory in express 
Javascript :: search partial string in array javascript 
Javascript :: python json string to object 
Javascript :: convert 24 hours to 12 hours javascript 
Javascript :: send a message when a bot joins your server discord.js 
Javascript :: how to update node js version 
Javascript :: how to view sync storage in chrome 
Javascript :: remove empty or whitespace strings from array javascript 
Javascript :: array of objects sahould have unique values 
Javascript :: How to get convert number to decimal - jquery 
Javascript :: how to see if a web site is useing react 
Javascript :: moment is not defined 
Javascript :: js how to check typeof boolean 
Javascript :: adding integers jquery 
Javascript :: reactive localstorage in react 
Javascript :: how to set height dynamically in jquery 
Javascript :: javascript get number from input 
Javascript :: mui theme remove shadow 
Javascript :: js input text set value 
Javascript :: detect fullscreen mode 
Javascript :: javascript get date without time 
Javascript :: react native loading 
Javascript :: create react app and tailwind 
Javascript :: add array to localstorage 
Javascript :: vue prop array default 
Javascript :: how to filter through array extracting only numbers in js 
Javascript :: node js send file from root dir 
Javascript :: updatedAt 
Javascript :: javascript friendly number format with commas 
Javascript :: javascript iterate object key values 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =