Swift 3 array - remove multiple elements with help of other array - ios

Swift 3:
I've two arrays, one is an array of the dictionary(json) and another is of indexes (Int value) of index Path (Collection type Index with element row & section). With the help of index rows of the second array, I need to remove, elements from the first array.
var arrayString = [ // Array with Json elements
{ "name" : "A" },
{ "name" : "B" },
{ "name" : "C" },
{ "name" : "D" },
{ "name" : "E" },
{ "name" : "F" },
{ "name" : "G" },
{ "name" : "H" }
]
Now Second array (to be removed from the first array)
var arrayIndex = [ 2, 3, 5 ] // Array with
How can I do this?
I want resulting array like
var arrayString = [
{ "name" : "A" },
{ "name" : "D" },
{ "name" : "F" },
{ "name" : "G" },
{ "name" : "H" }
]

Your array arrayIndex is look like Array of Int not array of IndexPath.
arrayIndex.sorted(by: >).forEach { if $0 < self.arrayString.count { self.arrayString.remove(at: $0) } }
If arrayIndex is Array of IndexPath then use row property to remove the object from array.
arrayIndex.sorted(by: { $0.row > $1.row }).forEach { if $0.row < self.arrayString.count { self.arrayString.remove(at: $0.row) } }

Here's a functional approach using enumerated, filter, contains, and map to create the array:
var arrayString = [
[ "name" : "A" ],
[ "name" : "B" ],
[ "name" : "C" ],
[ "name" : "D" ],
[ "name" : "E" ],
[ "name" : "F" ],
[ "name" : "G" ],
[ "name" : "H" ]
]
let arrayIndex = [2, 3, 5]
arrayString = arrayString.enumerated()
.filter { !arrayIndex.contains($0.0 + 1) }
.map { $0.1 }
print(arrayString)
[["name": "A"], ["name": "D"], ["name": "F"], ["name": "G"], ["name": "H"]]
Explanation:
.enumerated() takes the original array and creates an array of tuple pairs containing the index of each item paired with the item: (index, item)
filter selects those items from the resulting array that return true from the passed (trailing) closure. In this case, an item is selected if its index is not in arrayIndex
map is used to pull just the item from the resulting array of tuples
the index was increased by 1 because your example seemed to indicate that your arrayIndex started at 1 and not 0

Related

List Add Map Object

I have two lists as below. How can I combine the elements in the list within themselves?
var cars = [
{"id" : 1, "title" : "BMW"},
{"id" : 2, "title" : "Toyota"}
];
var attr = [{"hp" : 250}, {"hp" : 130}];
How can I get it to print out this way?
[{"id": 1, "title": BMW", "hp": 250}, {"id": 2, "title": "Toyota", "hp": 130}]
I assume both list have same number of items and each item needs to be merged to the item at the same index on the other list.
In that case, you can either use a for loop to iterate through those lists and merge or you can just use forEach method.
cars.asMap().forEach((index, value) => () {
return value.addAll(attr[index]);
}());
print(cars);
Output:
[{id: 1, title: BMW, hp: 250}, {id: 2, title: Toyota, hp: 130}]
var cars = [
{"id" : 1, "title" : "BMW"},
{"id" : 2, "title" : "Toyota"}
];
var attr = [{"hp" : 250}, {"hp" : 130}];
var newList = [];
for (int i=0;i<cars.length;i++){
Map newCar = {
"id":cars[i]["id"],
"title":cars[i]["title"],
"hp":attr[i]["hp"],
};
newList.add(newCar);
}
print(newList);
For me, that's the simplest solution that comes to my mind
If you want to do it without using a third list then you must follow this. This is simple logic and can be used for larger lists as well.
List<Map> cars = [
{"id" : 1, "title" : "BMW"},
{"id" : 2, "title" : "Toyota"}
];
List<Map> attr = [{"hp" : 250}, {"hp" : 130}];
for(int i = 0; i<cars.length;i++){
for(int j = 0; j<attr.length;j++){
if(i==j){
cars[i].addAll(attr[j]);
}
}
}
print(cars);

Getting nested children from Firebase Database

I am attempting to populate a table view with values from my Firebase database. I was able to use queryOrdered on the root of my database to get the children I required, as seen here:
func oneTimeInit() {
databaseRef?.queryOrdered(byChild: "Seasons").observe(.value, with:
{ snapshot in
for item in snapshot.children {
self.seasons.append(Season( snapshot: item as! DataSnapshot))
}
self.seasonsTableView.reloadData()
})
}
But now I am trying to get the children of the next node in my database. I tried to do this by calling queryOrdered on the child of the root but I'm not getting any data. Here is my code:
func oneTimeInit() {
databaseRef?.child("Seasons").queryOrdered(byChild: season.name).observe(.value, with:
{ snapshot in
for item in snapshot.children {
print("ITEM VALUE: \(item)")
self.races.append(Race(snapshot: item as! DataSnapshot))
}
self.racesTableView.reloadData()
})
}
The Database contains, at its highest level, Cross Country Seasons, which each contain Cross Country Races, which each contain results. Im able to populate the Seasons table but not the Races table, and so on.
Heres the Json structure of my database:
{
"Seasons" : {
"XC 2018" : {
"NCAA DI West Regional" : {
"Men" : {
"Results" : {
"Aaron BRUMBAUGH" : {
"finishTime" : "31:59.0",
"lapTimes" : [ "5:05.1", "10:43.3", "11:07.1", "5:03.5" ],
"name" : "Aaron BRUMBAUGH",
"position" : "118",
"splitTimes" : [ "5:05.1", "15:48.4", "26:55.5", "31:59.0" ],
"team" : "Santa Clara",
"year" : "SR"
},
"Addison DEHAVEN" : {
"finishTime" : "29:47.8",
"lapTimes" : [ "4:58.2", "10:14.0", "10:04.1", "4:31.5" ],
"name" : "Addison DEHAVEN",
"position" : "7",
"splitTimes" : [ "4:58.2", "15:12.2", "25:16.3", "29:47.8" ],
"team" : "Boise State",
"year" : "SR"
},
"Ahmed MUHUMED" : {
"finishTime" : "30:08.1",
"lapTimes" : [ "4:58.6", "10:14.6", "10:08.5", "4:46.4" ],
"name" : "Ahmed MUHUMED",
"position" : "29",
"splitTimes" : [ "4:58.6", "15:13.2", "25:21.7", "30:08.1" ],
"team" : "Boise State",
"year" : "SO"
},
As of now there is only one "Season" (XC 2018) with one "Race" (NCAA D1 West Regional). I'm trying to get a reference to all of the "Races" under the "Season" XC 2018.
The variable season.name would contain the value "XC 2018". With my second one time init I am trying to look at the children of "XC 2018".

Query object in child array

I am trying to use a query to retrieve data of student who are only 4 years old from my database but i cant figure out how to use Firebase to query the age (The array in each child).
{
"student" : {
"-Kv2RVDDsI-v6V7g_LBn" : [ {
"name" : "sam",
"age" : "6"
}, {
"name" : "tom",
"age" : "4"
}
],
"-hguyu-v6V7g_LBn" : [ {
"name" : "Tim",
"age" : "12"
}, {
"name" : "tom",
"age" : "4"
}
]
}
}
This is my code but it does no return anything.
ref.child("student").queryOrdered(byChild: "age").queryEqual(toValue: 4).observe(.childAdded, with: { (snapshot) in
let value = snapshot.value
print(value)
}) { (error) in
print(error.localizedDescription)
}
However, if i remove the queryOrdered(byChild: "age") it works.
Thanks.
You are referencing "Student" when actually your JSON database format child path name is "Students".
Also make sure that you are querying by key. Refer to the Firebase documentation to see how to query by key. I don't understand your structure though why you have 2 children per key.
Why not have a new key for each child?

no implicit conversion of String into Integer (TypeError)

Sorry for novice question, i am a beginner in JSON.
I have the following json:
{
"destination_addresses" : [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, Washington, États-Unis" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 707 km",
"value" : 1707145
},
"duration" : {
"text" : "3 jours 19 heures",
"value" : 327471
},
"status" : "OK"
},
]
},
],
"status" : "OK"
}
and i am going to get duration value.
i used this line
duration = json["rows"][0]["elements"]["duration"]["text"]
but i am facing with this erorr
no implicit conversion of String into Integer (TypeError)
Looking at the example JSON, elements is an array:
"elements" : [...
so needs to be indexed numerically e.g.
duration = json["rows"][0]["elements"][0]["duration"]["text"]
currently the string "duration" is being used to index into the elements array leading to the error you're seeing.

Neo4j Cypher: Importing nested collection by getting Error: Unable to deserialize request: Unexpected character code 99

I have nested collection and I add "Data" then foreach "Data" I add its own "Tags". I found unwind for "Data" with foreach for "Tags".
I wanna add person which I import its info from outside of collection manually.
I execute below Cypher query by statements:
I have imitated from:
Cypher Import Statement
AND
Cypher Unwind
I checked my json via enter link description here And it is validated.
{ "statements": [ { "statement": " WITH { "categories": [ {"dataid" : "11" , "dataname" : "data1" , "datalanguage" : "en" , "datatype" : "type1" ,"content" : "content1" , "tags" : [{"myid" : "11" , "tagid" : 10 , "tagname" : "tag1" }] } , {"dataid" : "22" , "dataname" : "data2" , "datalanguage" : "en" , "datatype" : "type2" ,"content" : "content2" , "tags" : [{"myid" : "22" , "tagid" : 20 , "tagname" : "tag2" }] } ] } AS document UNWIND document.categories AS category MERGE (dt:Data {name: category.dataname}) ON CREATE SET dt.id = category.dataid , dt.type = category.datatype , dt.language = category.datalanguage , dt.content = category.datacontent MERGE (p:Person { name : 'Mahsa' , lastname : 'Mahsa' } ) ON CREATE SET p.id =1 MERGE (p)-[r:owner]->(dt) FOREACH (mytag IN category.tags | MERGE (t:Tag {name: mytag.tagname}) ON CREATE SET t.id = mytag.tagid MERGE (dt)-[r2:tagged { Freq : 12 ]->(t) )" } ] }
But it returns as result: (I checked many times for "Unexpected character" but I could not find )
{"results":[],"errors":[{"code":"**Neo.ClientError.Request.InvalidFormat**","message":"**Unable to deserialize request: Unexpected character ('c' (code 99)): was expecting comma to separate OBJECT entries**\n at [Source: HttpInputOverHTTP#132e16b; line: 1, column: 48]"}]}
I made my nested collection as:
string dataCollection2 = "{ \"categories\": [ {\"dataid\" : \"11\" , \"dataname\" : \"data1\" , \"datalanguage\" : \"en\" , \"datatype\" : \"type1\" ," +
"\"content\" : \"content1\" , \"tags\" : [{\"myid\" : \"11\" , \"tagid\" : 10 , \"tagname\" : \"tag1\" }] }" +
" , {\"dataid\" : \"22\" , \"dataname\" : \"data2\" , \"datalanguage\" : \"en\" , \"datatype\" : \"type2\" ," +
"\"content\" : \"content2\" , \"tags\" : [{\"myid\" : \"22\" , \"tagid\" : 20 , \"tagname\" : \"tag2\" }] } ] }";
var obj1 = JValue.Parse(#"'" + dataCollection2 + "'");
I imported my json to http://jsonlint,com and I got it is validated:
{
"categories": [
{
"dataid": 11,
"dataname": "data1",
"datalanguage": "en",
"datatype": "type1",
"content": "content1",
"tags": [
{
"myid": 11,
"tagid": 10,
"tagname": "tag1"
}
]
},
{
"dataid": 22,
"dataname": "data2",
"datalanguage": "en",
"datatype": "type2",
"content": "content2",
"tags": [
{
"myid": 22,
"tagid": 20,
"tagname": "tag2"
}
]
}
]}
The fundamental problem with the string you are passing to the REST API is that you are not passing a legal Cypher query. Cypher property "maps", which look a bit like JSON, are NOT JSON.
In your case, the important difference is that property names must NOT be delimited by double-quotes. Only string property values can be delimited by double-quotes.
So, categories, dataId, dataName, etc., must not be surrounded by double-quotes.
You also have a typo near the end of the query. [r2:tagged { Freq : 12 ] should be [r2:tagged { Freq : 12} ].
For Adding nested collection to neo4j:
Firstly: For having right input to neo4j as parameter I must remove "{
"categories": [ ] }" from the first and the end of json.
Secondly: I should put this json as parameter to statement
Thirdly: I have to use two "UNWIND and WITH" (instead of using foreach) for separating each row from collection either for parent or for child.
"Foreach" DOES similar to "UNWIND and WITH".
My final collection and query are:
Collection:
{"id" : 1, "name" : "Data1", "language" : "en", "tags": {"id" : 11, "name": "tag 11" } } , {"id" : 2, "name": "Data2" , "tags": [ {"id" : 33, "name": "tag 33"} , {"id" : 44, "name": "tag44"} ] }
Query:
{ "statements": [ { "statement": " UNWIND { datas } AS data MERGE (p:Person { name : 'God' , lastname : 'God' } ) ON CREATE SET p.id =2 MERGE (d:Data {name: data.name}) ON CREATE SET d.id = data.id , d.language = data.language MERGE (p)-[r:owner]->(d) WITH d, data.tags AS mytags UNWIND mytags AS mytag MERGE (t:Tag {name: mytag.name}) ON CREATE SET t.id = mytag.id MERGE (d)-[r2:tagged { Freq : 12 } ]->(t) " , "parameters": { "datas" : [{"id" : 1, "name" : "Data1", "language" : "en", "tags": {"id" : 11, "name": "tag 11" } } , {"id" : 2, "name": "Data2" , "tags": [ {"id" : 33, "name": "tag 33"} , {"id" : 44, "name": "tag44"} ] }] } } ] }

Resources