_.groupBy

Group items by key.

  1. // Underscore/Lodash
  2. var grouped = _.groupBy(['one', 'two', 'three'], 'length')
  3. console.log(grouped)
  4. // output: {3: ["one", "two"], 5: ["three"]}
  5.  
  6. // Native
  7. var grouped = ['one', 'two', 'three'].reduce((r, v, i, a, k = v.length) => ((r[k] || (r[k] = [])).push(v), r), {})
  8. console.log(grouped)
  9. // output: {3: ["one", "two"], 5: ["three"]}
  1. // Underscore/Lodash
  2. var grouped = _.groupBy([1.3, 2.1, 2.4], num => Math.floor(num))
  3. console.log(grouped)
  4. // output: {1: [1.3], 2: [2.1, 2.4]}
  5.  
  6. // Native
  7. var grouped = [1.3, 2.1, 2.4].reduce((r, v, i, a, k = Math.floor(v)) => ((r[k] || (r[k] = [])).push(v), r), {})
  8. console.log(grouped)
  9. // output: {1: [1.3], 2: [2.1, 2.4]}

Browser Support for Array.prototype.reduce()

ChromeEdgeFirefoxIEOperaSafari
3.0 ✔9.0 ✔10.5 ✔4.0 ✔