Kristofer
Kristofer

Reputation: 817

How to sort array by the value of the arrays inside

I have an array that's like,

var array = [[CustomModel(set:2, name: "Apple"), CustomModel(set:2, name:"Orange")], [CustomModel(set:1, name:"Home"),CustomModel(set:1, name:"Building")]]

how do I sort the array to be like

var array = [[CustomModel(set:1, name:"Home"),CustomModel(set:1, name:"Building")], [CustomModel(set:2, name: "Apple"), CustomModel(set:2, name:"Orange")]]

so that the value of the set that is lower comes before the value of others.

Is this even possible? or is there a better way to do this.

Upvotes: 0

Views: 40

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51965

It's a plain sort if set is the same for all elements, then we can just pick the first element of the inner array to sort with

array.sort(by: {($0.first?.set ?? Int.max) < ($1.first?.set ?? Int.max)})

otherwise we need to pick one, like the smallest value

array.sort(by: { ($0.map {$0.set}.min() ?? Int.max) < ($1.map {$0.set}.min() ?? Int.max) })

Upvotes: 1

Related Questions