Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let array = [
  2.   {
  3.     id: "1",
  4.     name: "Table1",
  5.     color: "red"
  6.   },
  7.   {
  8.     id: "2",
  9.     name: "Table1",
  10.     color: "magenta"
  11.   },
  12.   {
  13.     id: "3",
  14.     name: "Table1",
  15.     color: "red"
  16.   },
  17.   {
  18.     id: "4",
  19.     name: "Table2",
  20.     color: "red"
  21.   }
  22. ];
  23.  
  24. let groupBy = (array, key) => {
  25.   let groups = [];
  26.   let set = new Set();
  27.   array.forEach(e => {
  28.     set.add(e[key]);
  29.   });
  30.   set.forEach(s => {
  31.     const [...el] = array.filter(f => f[key] === s);
  32.     groups.push(el);
  33.   });
  34.   return groups;
  35. };
  36.  
  37. let groupedArray = groupBy(array, "name");
  38.  
  39. let newArray = [];
  40. groupedArray.forEach( e => {
  41.     newArray.push(groupBy(e, "color"));
  42. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement