# Sorting an array based on the value of a property

**URL:** <https://forums.swift.org/t/sorting-an-array-based-on-the-value-of-a-property/28911>\
**Category:** Using Swift\
**Created:** [September 17, 2019, 8:44pm UTC](https://forums.swift.org/t/sorting-an-array-based-on-the-value-of-a-property/28911 "2019-09-17T20:44:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kmyhre](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmyhre/32/9019_2.png) [@kmyhre](https://forums.swift.org/u/kmyhre)\
**Post date:** [September 17, 2019, 8:44pm UTC](https://forums.swift.org/t/sorting-an-array-based-on-the-value-of-a-property/28911/1 "2019-09-17T20:44:13Z")

</div>

Hi everybody! Newbie here, trying to figure this one out.

Let’s say I have a struct `Foo` with a couple of members, one of which is an array.

```
struct Foo {
let name: String
let numbers: [Float]
}

```

And the array `bar` contains two instances of this type:

```
bar.append(Foo(name: “One”, numbers: [5, 3, 1]))
bar.append(Foo(name: “Two”, numbers: [6, 4, 2]))

```

How can I sort the array `bar` based on the contents of `numbers[0]`? From what I can see, neither `sort()` nor `sort(by:)` has an easy way to do this. Am I just structuring my data in a very odd way, or should there be an accessible way to do this?

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [September 17, 2019, 8:46pm UTC](https://forums.swift.org/t/sorting-an-array-based-on-the-value-of-a-property/28911/2 "2019-09-17T20:46:39Z")

</div>

`sort(by:)` is probably the easiest right now, other than conforming `Foo` to `Comparable`.

```swift
sort { $0.numbers[0] < $1.numbers[0] }

```

There's also this pitch: [Map Sorting](https://forums.swift.org/t/map-sorting/21421)

---

<div class="post-metadata">

**Author:** ![kmyhre](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmyhre/32/9019_2.png) [@kmyhre](https://forums.swift.org/u/kmyhre)\
**Post date:** [September 17, 2019, 11:24pm UTC](https://forums.swift.org/t/sorting-an-array-based-on-the-value-of-a-property/28911/3 "2019-09-17T23:24:37Z")

</div>

Works like a charm, thank you!
