Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group items from array that match, into another array?

Tags:

arrays

swift

For example say I have an array like so:

var someArray = ["1", "1", "2"]

I need to put this into two arrays that look like:

["1","1"]

["2"]

How can I go about this?

Any help would be great!

like image 204
farhan Avatar asked Jan 29 '23 04:01

farhan


1 Answers

Use Dictionary initializer init(grouping:by:) Then just get arrays by accessing values property.

Example:

let dic = Dictionary(grouping: someArray) { $0 }
let values = Array(dic.values)
print(values)

Result:

[["2"], ["1", "1"]]
like image 159
kirander Avatar answered Feb 01 '23 00:02

kirander