-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 }]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
EMV
  • 37
  • 5
  • 1
    `let sorted = notSortArrayObject.sorted(by: { sortArray.firstIndex(of: $0.id) ?? Int.max < sortArray.firstIndex(of: $1.id) ?? Int.max })` should do the trick – Larme Apr 08 '22 at 16:59
  • Does this answer your question? [Reorder array compared to another array in Swift](https://stackoverflow.com/questions/39273370/reorder-array-compared-to-another-array-in-swift) – Larme Apr 08 '22 at 17:01

2 Answers2

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})
atultw
  • 921
  • 7
  • 15
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 }
            }
HunterLion
  • 3,496
  • 1
  • 6
  • 18