Custom sort objects in an array in swift - arrays

Needed to sort Objects (Class/Datatype), Alphabetically.
UnSorted Array::
[main.Apple, main.Zoo, main.IceCream, main.Apple, main.IceCream]
Sorted Array:: Alphabetically Type # the Front
[main.Apple, main.Apple, main.IceCream, main.IceCream, main.Zoo]

This is one of the solutions that I have found till now:
Make use of sortInPlace function and dynamicType to check for class names e.g.:- String(firstDataType.dynamicType).componentsSeparatedByString(".").last! this retrieves the class name for the Object.
unsortedArray.sortInPlace({(firstDataType,secondDataType) in
return String(firstDataType.dynamicType).componentsSeparatedByString(".").last!
.localizedStandardCompare(String(secondDataType.dynamicType).componentsSeparatedByString(".").last!) == NSComparisonResult.OrderedAscending
})
Demo Link

Related

Sorting a 2 dimensional array of objects in Kotlin

I have a static 2 dimensional array of objects in a Kotlin project:
class Tables {
companion object{
lateinit var finalTable: Array<Array<Any?>?>
}
}
It is a little clearer in Java:
public class Tables {
public static Object[][] finalTable;
}
The third element in one row of objects in the table, is a string boxed as an object. In other words: finalTable[*][2] is a string describing the item. When I add an item to the array in Kotlin, I want to sort the entire array in alphabetical order of the description.
In Java this is easy:
Arrays.sort(Tables.finalTable, Comparator.comparing(o -> (String) o[2]));
When I try to use Android Studio to translate the Java code into Kotlin, it produces the following:
Arrays.sort( Tables.finalTable, Comparator.comparing( Function { o: Array<Any?>? -> o[2] as String }) )
This does not work, you have change the String cast as follows:
Arrays.sort( Tables.finalTable, Comparator.comparing( Function { o: Array<Any?>? -> o[2].toString() }) )
This version will compile and run, but it totally messes up the sorting of the table, so it does not work. I have tried variations on this theme, without any success. To get my project to work, I had to create a Java class in the Kotlin project with the functional Java code listed above:
public class ArraySort {
public void sortArray(){
Arrays.sort(Tables.finalTable, Comparator.comparing(o -> (String) o[2]));
}
}
This sorts the table like a charm, but I would prefer to keep my project "pure Kotlin". Can anyone suggest a pure Kotlin method to sort such an array? Thanks!
Unless I'm missing something, you can just do this:
Tables.finalTable.sortBy { it[2] as String }
which sorts your array in place. sortedBy will produce a new copy of the original if that's what you want instead, and might be why the comment suggestions weren't working for you.
But this whole unstructured array situation isn't ideal, the solution is brittle because it would be easy to put the wrong type in that position for a row, or have a row without enough elements, etc. Creating a data structure (e.g. a data class) would allow you to have named parameters you can refer to (making the whole thing safer and more readable) and give you type checking too

Iterate through an array in an array of dictionaries swift

I am currently in a bit of a bind.
struct sectionWithDatesAsName {
var sectionName : String
var sectionObjects : [SoloTransactionModel]!
init(uniqueSectionName: String?, sectionObject: [SoloTransactionModel]?) {
sectionName = uniqueSectionName ?? "nil"
if let section = sectionObject {
sectionObjects = section.reversed()
}
}
}
I currently have an array of sectionWithDatesAsName. And I can work with it, display in the tableView among other things.
The bind comes up when I want to check some information in the sectionObject before displaying it on the tableView.
I want to check the type of the sectionObject which is saved in the object itself.
How do I check the information in the sectionObject without slowing down the app? Or have a horrible time complexity calculated?
(Note: I can't change the format of the struct has this has already been used by a whole lot of other processes)
Write a function in your sectionWithDatesAsName with the signature filteredSections(type: sectionType) -> sectionWithDatesAsName
(If you don't have the ability to edit the definition of sectionWithDatesAsName you can create an extension that adds the above function)
If the sectionWithDatesAsName is defined elsewhere, define this function in an extension.
When you call it, build a new sectionWithDatesAsName object by filtering the arrays to match the specified type.
Use the resulting filtered sectionWithDatesAsName object as the data model for your table view. It will be built once and used for the lifetime of the tableView, so you will pay an O(n) time cost to filter it once when you create it.

Swift 3 - set the key when appending to array

I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).
var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
]
I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like
colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
The line above doesn't work, it is just to illustrate what I need.
Thanks for any help
Update: the code above is an example. Below the real code:
var placedBeacons : [BeaconStruct] = []
BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in
for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item
}
})
Error: Cannot subscript a value of type '[BeaconStruct]' with an index of type String
To match the key subscripting
self.placedBeacons["\(item.major):\(item.minor)"] = item
you have to declare placedBeacons as dictionary rather than an array
var placedBeacons = [String:BeaconStruct]()
It requires that item is of type BeaconStruct
The code you wrote, it should work. I have used such kind of code and was able to implement successfully. I just tested your code in my end and it's working for me. I declared colors variable globally in my class file and in view did load method added the second code to add another item in my colors array. After printing it out. My output shows full list of array with 4 items and the number of array count return 4 as well.
Please let me know, more details of your scenario so i can help you to figure it out the issue. but looks like it should work.

sort a table with special characters in angularjs

How can I sort an object based on a property when that property contains special characters such as ä,ü,ö in angularjs using orderBy?
For example if I sort the object users based on the name property,
$scope.users = [
{name:'A', value:'1'},
{name:'B', value:'2'},
{name:'Ä', value:'3'},
{name:'Ü', value:'4'},
{name:'U', value:'5'}
];
it should return:
{name:'A', value:'1'},
{name:'Ä', value:'3'},
{name:'B', value:'2'},
{name:'U', value:'5'},
{name:'Ü', value:'4'}
Sort order is determined doing a lexicographical sort by comparing Unicode (z: U+005A comes before e: U+0065).
Have a look at this article which presents two different solutions to your problem.

Sorting Multidimensional Array in Actionscript

I have an array of arrays that I need to sort, but I'm having trouble getting it figured out. My main array (mainArr) looks like this:
mainArr = ({code:"1", date:"1/2/2001", status:"Active"},
{code:"2", date:"6/2/2004", status:"Terminated"},
{code:"3", date:"2/2/2003", status:"Transferred"},
{code:"4", date:"9/2/2003", status:"Active"});
I need to sort the mainArr by the dates in the objects. The list should end up like this:
mainArr = ({code:"1", date:"1/2/2001", status:"Active"},
{code:"3", date:"2/2/2003", status:"Transferred"},
{code:"4", date:"9/2/2003", status:"Active"}.
{code:"2", date:"6/2/2004", status:"Terminated"});
In most cases, you can use the sortOn method of Array. For instance, if you wanted to sort by 'code':
mainArr.sortOn("code");
This will sort the array using the code field of each object to determine the order.
However, as you wish to sort by dates (in a string format), sorting will give incorrect results (as ordering alphabetically and in date order are not the same). You could add a new property to each object in the array to make sorting easier, eg:
{code:"1", date:"1/2/2001", status:"Active"}
Adding the date in reverse order (sortableDate), it would become:
{code:"1", date:"1/2/2001", status:"Active", sortableDate:"2001/2/1"}
and you can then order with:
mainArr.sortOn("sortableDate");

Resources