按某些属性对数组的元素进行分组 [英] Group elements of an array by some property

查看:68
本文介绍了按某些属性对数组的元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性为 date 的对象数组.

I have an array of objects with property date.

我想要的是创建数组数组,其中每个数组将包含具有相同日期的对象.

What I want is to create array of arrays where each array will contain objects with the same date.

我知道,我需要像 .filter 这样的东西来过滤对象,然后 .map 将所有东西添加到数组中.

I understand, that I need something like .filter to filter objects, and then .map to add every thing to array.

但是如何告诉 .map 我想要从过滤的对象中为每个组单独的数组,并且这个数组必须添加到全局"数组以及如何告诉 .filter 我想要具有相同日期的对象?

But how to tell .map that I want separate array for each group from filtered objects and that this array must be added to "global" array and how to tell .filter that I want objects with the same date ?

推荐答案

可能晚了,但新的 Xcode 9 sdk 字典有新的 init 方法

It might be late but new Xcode 9 sdk dictionary has new init method

init<S>(grouping values: S, by keyForValue: (S.Element) throws -> Key) rethrows where Value == [S.Element], S : Sequence

文档有这个方法的简单示例.我只是在下面发布了这个例子:

Documentation has simple example what this method does. I just post this example below:

let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })

结果将是:

["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]

这篇关于按某些属性对数组的元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆