Sorting an Array - iphone

I have an array containing all string values. Contents of the array are order_id, waypoint_x, waypoint_y. How do I sort it based on order_id and have the results like 1, 2, 3, 4.... (i.e. as if the field was an integer type and string)
When I use the waypoints as the array is at the moment the results come out 1, 10, 11, 12...
Regards,
Stephen

If you check the documentation of NSArray, you'll see there are different methods for sorting the array: sortedArrayUsingFunction, sortedArrayUsingSelector, sortedArrayUsingComparator, etc.
There's a nice example of how to use sortedArrayUsingFunction to sort with integer values in the answer to this question: Sorting an array of doubles or CLLocationDistance values on the iPhone

Related

How to map a jsonb array of numbers to a jsonb array of strings?

I have a jsonb array of numbers or strings, e.g. '[1, "2", 3]'::jsonb
I want to map all values to strings, so that I can end up with '["1", "2", "3"]'::jsonb
I tried this:
select jsonb_agg(jsonb_array_elements_text('[1, 2, 3]'::jsonb))
But it is complaining
LINE 1: select jsonb_agg(jsonb_array_elements_text('[1, 2, 3]'::json...
^
HINT: You might be able to move the set-returning function into a LATERAL FROM item.
Do what the error message suggests: use the set returning function jsonb_array_elements_text() like a table:
select jsonb_agg(element)
from jsonb_array_elements_text('[1, 2, 3]'::jsonb) as x(element);

Swift 5 Firebase queryOrderedBy String value

is it possible to query after the child value if its a string? In alphabetically order?
Doesnt matter whether it is descending or ascending.
e.g. under the key, each reference has the assigned name of the follower, and I want to order all the followers alphabetically.
Only manage to query it ordered by an integer unfortunately. (INCLUDING PAGINATION)
If this doesnt work, is there a way to query ordered by key? e.g. I have key 1 "-edasMmaed" and key 2 "-deLkdnw" etc and that if do paginate I start after the last value?
I haven't found anything useful unfortunately.
Kind regards
Edit: This is for the first part of the question
EDIT 2:
var query = Ref().databaseFollowingForUser(uid: userId, type: type).queryOrderedByKey()
if let latestUserFollowers = uid, latestUserFollowers != 0 {
query = query.queryEnding(atValue: latestUserFollowers).queryLimited(toLast: limit)
} else {
query = query.queryLimited(toLast: limit)
}
query.observeSingleEvent(of: .value, with: { (snapshot) in
With this code I receive the first 10 results (limit is defined as 10)
everbody from ID: 276 through ID: 18. (starting at holgerhagerson and ending at manni85)
Now I want to paginate and load more which I am not able yet.
The passed uid is the uid of the latest fetched user which is "18", manni85
BIG EDIT: I managed to order it by keys. Reading your answers regarding keys are always saved as strings, I realized my mistake and are now able to do it properly.
Big thank you!
Keys in the Firebase Realtime Database are stored (and sorted) as strings. Even if they look like numbers to you, Firebase will store (and sort) them as strings.
This means that the 2, 3, 4, etc in your screenshot are actually "2", "3", "4" etc. This affects how they are ordered, as strings are ordered lexicographically and in that order these keys will show up as "3", "30", "4", "44", "5", etc.
If you want to use keys that you can sort numerically, take these steps:
Prefix keys with a short non-numeric prefix, to prevent Firebase interpreting them as an array.
Use a fixed length for the numbers in all keys, prefixing the value with zeroes or spaces as needed.
When combined, your keys would show up as:
"key_003": ...,
"key_004": ...,
...
"key_008": ...,
"key_016": ...,
"key_018": ...,
"key_030": ...,
"key_044": ...
Which you can now reliably sort when you query /FOLLOW/Follower/2 by calling queryOrderedByKey().

Is jsonb conversion to text deterministic?

This is the short version of an overly long question that sadly attracted no answers.
Is it possible, given two jsonb variables x and y, to have both
1. (x = y) yield true, and
2. (x::text = y::text) yield false
I ask this question because it appears there is no promised order in which a jsonb object will be unpacked into a string. I'd just like to be sure this is the case.
Thanks in advance for feedback!
Edit:
The original question covers the "why" for this question, but the skinny is that I hope to group data in different rows based upon a hash of many columns represented as text, some of which are jsonb.
I don't care which way the object comes in or which way it gets unpacked, but I do care if two jsonb fields which are equivalent as jsonb are not equivalent as text strings.
As it seems I cannot count on text representations to be presented in the same way, I've normalized out the jsonb field to a separate table with the jsonb field set as a unique index.
And if I write more here... this question will approach the length of the one it derives from!
Formally the order is not deterministic because of the JSON object definition:
An object is an unordered set of name/value pairs.
Practically it appears that objects are sorted by length of keys and then alphabetically:
with example(col) as (
values
('{"cc": 1, "ab": 1, "a": 1, "aa": 1, "b": 2, "abc": 1}'::jsonb)
)
select col::text
from example
col
-------------------------------------------------------
{"a": 1, "b": 2, "aa": 1, "ab": 1, "cc": 1, "abc": 1}
(1 row)
Note that this behavior is undocumented and may change in future releases (though it may seem unlikely).

Dictionary print key and value in Swift 4 [duplicate]

This question already has an answer here:
From which direction swift starts to read dictionaries? [duplicate]
(1 answer)
Closed 5 years ago.
Hello I tried a print dictionary items at Xcode9. Like this:
var items = ["Bear":"0", "Glass":"1", "Car":"2"]
for (key,value) in items{
print("\(key) : \(value)")
}
output:
Glass : 1
Bear : 0
Car : 2
Why output not like this: Bear: 0, Glass:1, Car:2
I dont understand this output reason.
Dictionary :
A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering.
Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.
Array - An array stores values of the same type in an ordered list.
Sets - A set stores distinct values of the same type in a collection with no defined ordering.
From Apple documentation
Dictionary in Swift is implemented as hash map. There is no guarantee that items in Dictionary will have the same order you added them.
The only container that retains the order of items is Array. You can use it to store tuples, like so:
var items : [(key: String, value: String)] = [(key: "Bear", value: "0"),(key: "Glass", value: "1"), (key: "Car", value: "2")]
Your iteration will work as expected, but you will lose Dictionary's ability to lookup items by subscript
Arrays are ordered collections of values.
Sets are unordered collections of unique values.
Dictionaries are unordered
collections of key-value associations.
So, You can not expect the same order, when you are iterating the values from Dictionary.
Reference to Collection Type
Dictionary collection isn't ordered, that is it simply doesn't guarantee to be ordered. But Array is. Dictionary adds values in discrete orders whereas Array adds values in continuous order.
You simply can't have an Array like this:
["a", "b", ... , "d", ... , ... , "g"] //Discrete index aren't allowed. You just can't skip any index in between.
Instead you have to have the above array like this:
["a", "b", "d", "g"]
To be able to get rid of this behavior, Dictionary (where you don't have to maintain previous indexes to have values) was introduced. So you can insert values as you like. It won't bother you for maintaining any index.

searching an element in an array without a loop in postgresql

Im writing a query for searching an element in an array. Search using "for" loop is not efficient because my array is having a lot of elements. Because of this the query is taking lot of time to execute. So can any one say how to search an element in an array without "for" loop which should be faster. I have to get the index on searching
Thanks,
Karthika
Use the ANY operator:
where 1 = ANY (array_column)
That will return all rows where array_column contains the value 1 at least once. If you want to check for multiple values, see Clodoaldo's answer.
If you create an index on that column, this should be very fast. Something like this:
create index on the_table using gin (the_array_column);
The following is inspired by the solution shown here: Finding the position of a value in PostgreSQL arrays
with sample_data (pk_column, array_data) as (
values
(1, array[1,2,3,4,5]),
(2, array[7,8,9,11]),
(3, array[5,4,3,2,1]),
(4, array[10,9,8,1,4,6]),
(5, array[7,8,9])
)
select *
from (
select pk_column,
unnest(array_data) as value,
generate_subscripts(array_data, 1) as array_index
from sample_data
where 1 = any(array_data)
) t
where value = 1
The inner where will reduce the total work that needs to be done to only those rows that actually contain the value. The outer query will then "explode" the array to get the value's index. But using the function shown in the linked question might actually be what you are after.
Check the contains operator #>
select array[1,2] #> array[1];
?column?
----------
t
http://www.postgresql.org/docs/current/static/functions-array.html