Home > Back-end >  Sort an array of objects, following the order of another array that has a value of the objects of th
Sort an array of objects, following the order of another array that has a value of the objects of th

Time:04-09

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 }]

CodePudding user response:

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})

CodePudding user response:

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 }
            }
  • Related