Swift - new array based on result of comparing values of two arrays - arrays

idsArr = [ "id12345", "id27891", "id98654"]
idsNameIntvalueArr = [["id22913", "Peter Parker", 15], ["id12345", "Donald Duck", 6], ["id98654", "Mickey Mouse", 9], ["id112233", "Lion King", 9]]
I'm new in Swift, please give me advice, what is the best practice to compare this 2 arrays by id, if id matches, need to make new array with "name" and Int value, in this case:
resultArr = [["Donald Duck", 6],["Mickey Mouse", 9]]
Thanks.

You can do that like this:
let resultArr = idsNameIntvalueArr.filter({ idsArr.contains($0[0] as! String) }).map({ [$0[1], $0[2]] })
First, you need to filter the array to include only the members whose IDs exists in idsArr.
Then, after filtering the array you need to create sub-arrays that contains only the name and age, and this is what map does.

Related

Select filed from Array of Hashes in Ruby

So i have this Array of Hashes
{"id"=>50823, "code"=>"1PLAK", "name"=>"Eselente", "order"=>1}
{"id"=>74327, "code"=>"1MAGP", "name"=>"Mango", "order"=>2}
{"id"=>50366, "code"=>"1ANGC", "name"=>"Tabnie", "order"=>3}
{"id"=>76274, "code"=>"1FABD", "name"=>"Slamtab", "order"=>4}
And i want to select the field order (just one field at the same time) for comparing afterwards.
What's the correct way to do it?
Thanks!
When you only want to extract the values of the orders then I would do this:
array = [
{"id"=>50823, "code"=>"1PLAK", "name"=>"Eselente", "order"=>1},
{"id"=>74327, "code"=>"1MAGP", "name"=>"Mango", "order"=>2},
{"id"=>50366, "code"=>"1ANGC", "name"=>"Tabnie", "order"=>3},
{"id"=>76274, "code"=>"1FABD", "name"=>"Slamtab", "order"=>4},
]
array.map { |hash| hash["order"] }
#=> [1, 2, 3, 4]
When you are only interested in the very first value (1 like you wrote in the comments above) then you can do:
array.first["order"] # or array[0]["order"]
#=> 1

Sort order in Firestore arrays

I'm trying to understand arrays in Firebase a bit more. Currently, I'm storing maps in arrays, where one of the fields inside the map is a position that I can use in my mobile app to sort the array with on retrieval and show results in the order of position.
The docs on Firebase say:
Arrays are sorted by elements. If elements are equal, the arrays are sorted by length.
For example, [1, 2, 3] < [1, 2, 3, 1] < [2].
And then there's a section describing how maps are sorted as well:
Key ordering is always sorted. For example, if you write {c: "foo", a: "bar", b: "qux"} the map is sorted by key and saved as {a: "foo", b: "bar", c: "qux"}.
Map fields are sorted by key and compared by key-value pairs, first comparing the keys and then the values. If the first key-value pairs are equal, the next key-value pairs are compared, and so on. If two maps start with the same key-value pairs, then map length is considered. For example, the following maps are in ascending order:
{a: "aaa", b: "baz"}
{a: "foo", b: "bar"}
{a: "foo", b: "bar", c: "qux"}
{a: "foo", b: "baz"}
{b: "aaa", c: "baz"}
{c: "aaa"}
But then I tried this in Firestore: I jumbled up the order of the maps in the above example, and stored them in an array:
data= [{"c": "aaa"}, {"a": "aaa", "b": "baz"}, {"a": "foo", "b": "baz"}, {"b": "aaa", "c": "baz"}, {"a": "foo", "b": "bar", "c": "qux"}, {"a": "foo", "b": "bar"}]
And upon inserting into a Firestore document, the array did not get sorted! While the keys themselves do get sorted within a single Map, the elements in the array stay in the same order.
So does sorting in arrays even work when elements are Maps? Here's an example of what I'm storing in Firestore:
{
"car_collection": {
"models": {
data: [
{
"model": "Honda",
"color": "black",
"position": 0
},
{
"model": "Hyundai",
"color": "red",
"position": 1
},
{
"model": "Chevrolet",
"color": "yellow"
"position": 2
}
]
}
}
}
I'm storing an additional field called "position", and the order of maps stays the same on every retrieval. Wondering if I even need to store this field, or data will be sorted in the order that I store it in.
Submitted a ticket to Google to improve the documentation for Array type, and I think it's helpful and accurate as seen through some smoke testing.
https://firebase.google.com/docs/firestore/manage-data/data-types
Copy-pasting the current version here:
An array cannot contain another array value as one of its elements.
Within an array, elements maintain the position assigned to them. When sorting two or more arrays, arrays are ordered based on their element values.
When comparing two arrays, the first elements of each array are compared. If the first elements are equal, then the second elements are compared and so on until a difference is found. If an array runs out of elements to compare but is equal up to that point, then the shorter array is ordered before the longer array.
For example, [1, 2, 3] < [1, 2, 3, 1] < [2]. The array [2] has the greatest first element value. The array [1, 2, 3] has elements equal to the first three elements of [1, 2, 3, 1] but is shorter in length.
So it seems you can safely expect the order of elements to be maintained in Firestore, while understanding the effects of addition/removal as well.
You will have to sort your array before posting it to Firestore.
Arrays are not sorted in RTD nor Firestore objects however are sorted by it's keys.
Or sort the arrays on the client side.

Need to create an array of sets swift

I'm brand new to Swift, and it's been awhile since I've done any programming at all so please forgive me. I need some help on how to create an empty array that would contain a set of numbers.
What I'm trying to do is read two sets of numbers in from two different data files, and place them into two different data structures - in this case - arrays. I then want to loop through the array and determine if one group of numbers is a subset of the other. I have created the following code in the swift playground, and tested it and I know it can be done using pre-defined values in the code.
However, I can't seem to find anywhere online how to create an array of sets. I find all sorts of links that say when to use an array rather than a set and vice versa. When I try to declare an empty Array of type Set it gives me an error. I would appreciate anyone pointing me in the right direction. Here is the code that I typed into the playground that works.
var a: Set = [1,2]
var b: Set = [1,3]
var c: Set = [1,4]
var aa: Set = [1,4,23,29,50]
var bb: Set = [1,3,45,47,65]
var cc: Set = [7,9,24,45,55]
let combiArray = [a, b, c]
let resultsArray = [aa, bb, cc]
for i in 0...2 {
print (resultsArray[i],
combiArray[i],
combiArray[i].isSubset(of: resultsArray[i]))
}
Set is a generic type. When you say var a: Set = [1, 2], the compiler infers the necessary generic type parameter for you, making it equivalent to var a: Set<Int> = [1, 2]
To make an empty Array of Sets, you have to explicitly state what kind of Set you want, because the compiler can't infer it from the Set's contents. You're looking to make an empty Array<Set<Int>>, a.k.a. [Set<Int>].
Either:
let arrayOfSets: [Set<Int>] = []
or:
let arrayOfSets = [Set<Int>]() // preferred
Here's that reflected in your example:
let combiArray: [Set<Int>] = [ // TODO: What the heck is a "combi"?
[1, 2],
[1, 3],
[1, 4],
]
let results: [Set<Int>] = [
[1, 4, 23, 29, 50],
[1, 3, 45, 47, 65],
[7, 9, 24, 45, 55],
]
for (combi, result) in zip(combiArray, results) {
print("\(combi) \(combi.isSubset(of: result) ? "is" : "is not") a subset of \(result).")
}

Hash with key as an array type

How to create a key as array in Go for map.
For example in ruby I can implement it such:
quarters = {
[1, 2, 3] => 'First quarter',
[4, 5, 6] => 'Second quarter',
[7, 8 ,9] => 'Third quarter',
[10, 11, 12] => 'Fourh quarter',
}
quarters[[1, 2, 3]]
# => "First quarter"
How the same will be looked in Golang ?
Array types (unlike slices) in Go are comparable, so there is nothing magical in it: you can just define it like any other maps: map[KeyType]ValueType where KeyType will be [3]int and ValueType will be string.
The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.
m := map[[3]int]string{}
m[[3]int{1, 2, 3}] = "First quarter"
m[[3]int{4, 5, 6}] = "Second quarter"
m[[3]int{7, 8, 9}] = "Third quarter"
m[[3]int{10, 11, 12}] = "Fourth quarter"
fmt.Println(m)
Output:
map[[1 2 3]:First quarter [4 5 6]:Second quarter
[7 8 9]:Third quarter [10 11 12]:Fourth quarter]
Try it on the Go Playground.
To query an element:
fmt.Println(m[[3]int{1, 2, 3}]) // Prints "First quarter"
You can also create the map in one step:
m := map[[3]int]string{
[3]int{1, 2, 3}: "First quarter",
[3]int{4, 5, 6}: "Second quarter",
[3]int{7, 8, 9}: "Third quarter",
[3]int{10, 11, 12}: "Fourth quarter",
}
It should be noted that array in ruby and array in go are different data structures. Go array is not mutable, while ruby array is. Go slice is a lot more similar data structure to ruby array. However, you cannot use slices as keys in go, as pointed out in icza's answer.
So to answer your question:
How the same will be looked in Golang ?
It is impossible, you cannot have a dictionary that maps dynamic arrays to strings in go. However, you could convert slices to arrays and use them as keys, as very well explained by icza.

How do you store sets in Cassandra?

I'd like to convert this JSON to a data model in Cassandra, where each of the arrays is a set with no duplicates:
var data = {
"data1": {
"100": [1, 2, 3],
"200": [3, 4]
},
"data2": {
"k1", [1],
"k2", [4, 5]
}
}
I'd like to query like this: data["data1"]["100"] to retrieve the sets. Anyone know how you might model this in Cassandra? (The only thing I came up with was columns whose name was a set value and the value of the column was an empty string, but that felt wrong.)
It's not OK to serialize the sets as JSON or some other string, which would make this much easier.
Also, I should note that it's OK to split data1 and data2 into separate ColumnFamilies, it's not necessary that they're keys in the same one.
This sounds like a job for the SuperColumn.

Resources