在Coffeescript中,我将如何通过一个属性对对象数组进行分组

In Coffeescript, how would I group an array of objects by one property?

本文关键字:对象 属性 一个 数组 Coffeescript 何通过      更新时间:2023-09-26

假设我有一个对象数组,如下所示:

var array = [
    {name:"aaa", height:"20"},
    {name:"bbb", height:"100"},
    {name:"ccc", height:"20"},
    {name:"ddd", height:"20"},
    {name:"eee", height:"100"},
]

在这种情况下,我想按高度对其进行分组,所以我最终得到了一个不同的数组,它有组名,然后是该组中的每个项目,如下所示:

var grouped_by_height = [
    [{name:"aaa", height:"20"}, {name:"ccc", height:"20"}, {name:"ddd", height:"20"}],
    [{name:"bbb", height:"100"}, {name:"eee", height:"100"}]
]

我在JS/jQuery中写了一个很长的解决方案,但我想知道是否有一种快速简单的方法可以做到这一点,那就是Coffeescapet。

array = [
    {name:"aaa", height:"20"},
    {name:"bbb", height:"100"},
    {name:"ccc", height:"20"},
    {name:"ddd", height:"20"},
    {name:"eee", height:"100"},
]
# unique heights
uniq = array.reduce (memo, el) ->
  memo.push(el.height) if memo.indexOf(el.height) is -1
  memo
, []
# output grouped by height
out = [[obj for obj in array when obj.height is height][0] for height in uniq][0]

我不认为CoffeeScript中有什么特别的东西可以帮助你(或者至少没有什么可以解决困难的部分)。我可能会用Array.prototype.reduce来做这样的重物:

group_by_height = (groups, obj) ->
    groups[obj.height] ?= [ ]
    groups[obj.height].push(obj)
    groups
grouped_obj = array.reduce(group_by_height, { })
grouped_by_height = (v for k, v of grouped_obj)

不过,这并不能保证grouped_by_height中有任何特定的顺序,但可以通过添加一个排序步骤来解决这个问题:

by_height = (a, b) -> +a[0].height - +b[0].height
group_by_height = (v for k, v of grouped_obj).sort(by_height)

您将对数组数组进行排序,使ab成为数组,因此[0]将查看第一个元素。一元+运算符用于将字符串高度转换为数字高度,以便它们按照您可能期望的方式进行比较。

这就是我能够想到的。正如穆所说的,咖啡脚本并没有什么魔力,但有一些内置的东西可以帮助它。唯一的问题是,编译后的js版本最终会比用纯js编写的版本更长。

groupByKey = (array, key) ->
  grouped = {}
  for obj in array
    grouped[obj[key]] ?= []
    grouped[obj[key]].push obj
  Object.keys(grouped).map (group) ->
    grouped[group]

自己试试:

array = [
  {
    name: 'aaa'
    height: '20'
  }
  {
    name: 'bbb'
    height: '100'
  }
  {
    name: 'ccc'
    height: '20'
  }
  {
    name: 'ddd'
    height: '20'
  }
  {
    name: 'eee'
    height: '100'
  }
]
groupByKey = (array, key) ->
  grouped = {}
  for obj in array
    grouped[obj[key]] ?= []
    grouped[obj[key]].push obj
  Object.keys(grouped).map (group) ->
    grouped[group]
console.log groupByKey(array, 'height')

输出为:

[
  [
    { 
      name: 'aaa',
      height: '20' 
    },
    { 
      name: 'ccc',
      height: '20' 
    },
    { 
      name: 'ddd',
      height: '20' 
    } 
  ],
  [ 
    { 
      name: 'bbb',
      height: '100'
    },
    { 
      name: 'eee',
      height: '100' 
    }
  ]
]