-1

How could I sort an array of objects taking into account another array?

Example:

let sortArray = [90, 1000, 4520]

let notSortArrayObject = [ { id: 4520, value: 4 }, {id: 1000, value: 2}, {id: 90, value:10} ]

So I want an array equal notSortArrayObject but sortered by sortArray value


let sortArrayObject =[{id: 90, value:10} , {id: 1000, value: 2}, { id: 4520, value: 4 }]
2
  • 1
    let sorted = notSortArrayObject.sorted(by: { sortArray.firstIndex(of: $0.id) ?? Int.max < sortArray.firstIndex(of: $1.id) ?? Int.max }) should do the trick Commented Apr 8, 2022 at 16:59
  • 1
    Does this answer your question? Reorder array compared to another array in Swift Commented Apr 8, 2022 at 17:01

2 Answers 2

0

Here's an approach. For each number in the "guide" array, find a match in the not sorted and add it to the sortedObjectArray. Note that this ignores any values which don't have matches in the other array.

var sortedObjectArray: [Object] = [] // whatever your object type is

for num in sortArray {
    if let match = notSortArrayObject.first(where: {$0.id == num}) {
        sortedObjectArray.append(match)
    }
}

If you just want to sort by the id in ascending order, it's much simpler:

let sorted = notSortArrayObject.sorted(by: {$0.id < $1.id})
Sign up to request clarification or add additional context in comments.

Comments

0

I noticed that sortArray is already sorted - you could just sort notSortArrayObject by id, but I assume that's not the point of what you're looking for.

So, let's say that sortArray = [1000, 4520, 90] (random order), to make things more interesting.

You can iterate through sortArray and append the values that match the id to sortArrayObject.


            // To store the result
            var sortArrayObject = [MyObject]()
            
            // Iterate through the elements that contain the required sequence
            sortArray.forEach { element in
                
                // Add only the objects (only one) that match the element
                sortArrayObject += notSortArrayObject.filter { $0.id == element }
            }

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.