4

I wish to sort an array, and return an array of indexes and elements within the sorted array;

ie:

var filtered = self.existingOrders.sorted(by: { (eo1:ExistingOrder, eo2:ExistingOrder) -> Bool in
                return (eo1.value < eo2.value)
            }).index(0, offsetBy: 0)

This just gives me an index of a specific number.

I would like a sorted array of elements and indexes; so I can grab the necessary index and do manipulations on them.

How do I make it so I can do;

// pseduocode:

var filtered:(Index, Element) = self.existingOrders.sortByLowest.return(flatMap(index, element))

or possibily even chain an enumerator to help give me a list of all items indexed; post-sort?

ie:

 let filtered = self.existingOrders.sorted(by: { (eo1:ExistingOrder, eo2:ExistingOrder) -> Bool in
                return (eo1.value < eo2.value)
            }).enumerated().flatMap({ (offset:Int, element:ExistingOrder) -> (Int, ExistingOrder) in
                return (offset, element)
            })

I wish to get a sorted array and return an index and element to my filter variable.

How do I accomplish this?

Many thanks

1 Answer 1

6

If I understand your question correctly then you can use enumerated() to get a sequence of offset/element pairs and sort this according to the elements. Example:

let array = ["C", "A", "B"]

let sortedElementsAndIndices = array.enumerated().sorted(by: {
    $0.element < $1.element
})

print(sortedElementsAndIndices) // [(1, "A"), (2, "B"), (0, "C")]

The first element in each tuple is the index of the second tuple element in the original array.

In your case it would be something like

let sorted = self.existingOrders.enumerated().sorted(by: {
    $0.element.value < $1.element.value
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.