how to compare two arrays of strings - coffeescript

I have the following arrays of strings:
array1 = ["a", "b", "c"]
array2 = ["a", "c", "b"]
array3 = ["a", "b"]
array4 = ["a", "b", "c"]
How can I compare the arrays so that:
array1 is array2 #false
array1 is array3 #false
array1 is array4 #true

You can't use the keyword is (which compiles to ===), but you can add a new is method to the prototype of Array:
Array::is = (o) ->
return true if this is o
return false if this.length isnt o.length
for i in [0..this.length]
return false if this[i] isnt o[i]
true
Then use it like
array1 = ["a", "b", "c"]
array2 = ["a", "c", "b"]
array3 = ["a", "b"]
array4 = ["a", "b", "c"]
alert array1.is array2
alert array1.is array3
alert array1.is array4

Related

Why MongoDB db.view.distinct("value.sub.id") return two-dimensional array

When run db.view.distinct("value.sub.id") , values return shoudle like ["A", "B", "C"] Normally. Which conditions will return values [ ["A"], ["B"], ["C"] ] ?

Swift: how to reduce some sub-elements in a Set with a one-liner?

I have this model:
struct Class {
var field: [String: Field]
}
struct Field {
var type: String
}
And this array:
let classes: [Class] = [
Class(field: ["test": Field(type: "STRING"),
"test2": Field(type: "STRING"),
"test3": Field(type: "NUMBER")]),
Class(field: ["test": Field(type: "POINTER"),
"test2": Field(type: "STRING"),
"test3": Field(type: "STRING")]),
]
I would like to reduce all the types properties in a Set of Strings, I tried this:
let result = classes.map { $0.field.reduce([], { $0 + $1.value.type }) }
But instead of getting a set of strings:
What I would like to get
"STRING", "NUMBER", "POINTER"
I get an array of characters:
[["S", "T", "R", "I", "N", "G", "N", "U", "M", "B"....]]
What should I write instead? Thank you for your help
You can use flatMap to flatten the arrays of values and then use Set to get rid of non-unique values:
let result = Set(classes.flatMap { $0.field.values }.map { $0.type })
If you need an Array instead of a Set, you can simply wrap the above in Array()

How can I append to a specific dictionary within an array of dictionaries in swift?

My data structure:
var defs = [["a":"b","c":"d"],["e":"f","g":"h"]]
I have tried the following:
dict[1]["testKey"] = "testValue"
in an attempt to attain the following:
defs = [["a":"b","c":"d"],["e":"f","g":"h","testKey":"testValue"]]
This doesn't work though. Does anyone have a good solution?
You have a typo in your code (I see you're using dict instead of defs but this works fine:
var defs = [
[
"a": "b",
"c": "d"
],
[
"e": "f",
"g": "h"
]
]
defs[1]["key"] = "value"
print(defs[1]["key"]) // "Optional("value")\n"
var defs = [["a":"b","c":"d"],["e":"f","g":"h"]]
defs[1]["testKey"] = "testValue"
print(defs)
prints:
[["a": "b", "c": "d"], ["e": "f", "testKey": "testValue", "g": "h"]]
The elements contained within the defs array are of type Dictionary, which by definition is unordered. If the order is an issue, you have to use another collection type.

Concatenate dictionary values in Swift

I created a dictionary in Swift like:
var dict:[String : Int] = ["A": 1, "B": 2, "C": 3, "D": 4]
print(dict["A"]!)
The computer prints number 1, but how do I concatenate these values such that the output is 1234 instead of a single integer?
The key-value pairs in a Dictionary are unordered. If you want to access them in a certain order, you must sort the keys yourself:
let dict = ["A": 1, "B": 2,"C": 3,"D": 4]
let str = dict.keys
.sorted(by: <)
.map { dict[$0]! }
.reduce ("") { $0 + String($1) }
Or alternatively:
let str = dict.keys
.sorted(by: <)
.map { String(dict[$0]!) }
.joined()
No idea about the relative performance of the two as I haven't benchmarked them. But unless your dictionary is huge, the difference will be minimal.
let dict = ["A": 1, "B": 2, "C": 3, "D": 4]
for entry in dict.sorted()
{
print("\(entry.1)", terminator: "")
}

Swift Dictionary Multiple Key Value Pairs - Iteration

In Swift I want to make an array of dictionaries (with multiple key value pairs) and then iterate over each element
Below is the expected output of a possible dictionary. Not sure how to declare and intitialize it (somewhat similar to array of hashes in Ruby)
dictionary = [{id: 1, name: "Apple", category: "Fruit"}, {id: 2, name: "Bee", category: "Insect"}]
I know how to make an array of dictionary with one key value pair.
For example:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
to declare an array of dictionary, use this:
var arrayOfDictionary: [[String : AnyObject]] = [["id" :1, "name": "Apple", "category" : "Fruit"],["id" :2, "name": "Microsoft", "category" : "Juice"]]
I see that in your dictionary, you mix number with string, so it's better use AnyObject instead of String for data type in dictionary.
If after this code, you do not have to modify the content of this array, declare it as 'let', otherwise, use 'var'
Update: to initialize within a loop:
//create empty array
var emptyArrayOfDictionary = [[String : AnyObject]]()
for x in 2...3 { //... mean the loop includes last value => x = 2,3
//add new dictionary for each loop
emptyArrayOfDictionary.append(["number" : x , "square" : x*x ])
}
//your new array must contain: [["number": 2, "square": 4], ["number": 3, "square": 9]]
let dic_1: [String: Int] = ["one": 1, "two": 2]
let dic_2: [String: Int] = ["a": 1, "b": 2]
let list_1 = [dic_1, dic_2]
// or in one step:
let list_2: [[String: Int]] = [["one": 1, "two": 2], ["a": 1, "b": 2]]
for d in list_1 { // or list_2
print(d)
}
which results in
["one": 1, "two": 2]
["b": 2, "a": 1]
let airports: [[String: String]] = [["YYZ": "Toronto Pearson", "DUB": "Dublin"]]
for airport in airports {
print(airport["YYZ"])
}