Backbone JS find the minimum value - backbone.js

I have this json which populates my collection (TableListCollection) of models (TableModel)
{
"tables": [
{
"tableId": 15,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 10,
"bigBlindAmount": 20,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
},
{
"tableId": 16,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 20,
"bigBlindAmount": 40,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
},
{
"tableId": 17,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 40,
"bigBlindAmount": 60,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
}
]
}
I want to find the table with the minimum smallBlindAmount.
I see that I can use the _.min() but I can't figure out what I have to pass as an iterator.
Thanks in advance.

Either directly on the JSON
var json=...
var min = _.min(json.tables,function(item) {
return item.stakes.smallBlindAmount
});
console.log(min.stakes.smallBlindAmount);
or on your collection
var json=...
var c=new Backbone.Collection(json.tables);
var m=c.min(function(model) {
return model.get("stakes").smallBlindAmount
});
console.log(m.get("stakes").smallBlindAmount);
In both cases, the iterator is used to extract the values to be compared.

Related

How to Update Array dict Elements in mongodb based on another field

How can I update a value in a document based on applying functions to another field (which is in a different embedded document)?
With the sample data below, I want to
get the col field for the farm having id 12
multiply that by 0.025
add the current value of the statistic.crypt field
ensure the value is a double by converting it with $toDouble
store the result back into statistic.crypt
data:
{
"_id": {
"$oid": "6128c238c144326c57444227"
},
"statistic": {
"balance": 112570,
"diamond": 14,
"exp": 862.5,
"lvl": 76,
"mn_exp": 2.5,
"lvl_mn_exp": 15,
"coll_ms": 8047,
"all_exp": 67057.8,
"rating": 0,
"crypt": 0
},
"inventory": {
"farm": [{
"id": 12,
"col": 100,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 18:58:39"
}, {
"id": 14,
"col": 1,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 16:57:08"
}],
"items": []
},
...
}
My initial attempt is:
self.collection
.update_many({"inventory.farm.id": 12}, [{
"$set": {
"test": {
'$toDouble': {
"$sum": [
{'$multiply':["$inventory.farm.$[].col", 0.025]},
'$test'
]
}
} }
},])
This does not work as it applies to test rather than statistic.crypt, and I cannot figure out how to modify it to apply to statistic.crypt.
A field can be updated based on another in the following stages:
add a field containing the farm
set statistic.crypt to the result of the mathematical expression (applied to the newly embedded farm)
remove extra fields
In code:
self.collection.update_many({"inventory.farm.id": 12 }, [
{
$addFields: {
hh: {
$filter: {
input: "$inventory.farm",
as: "z",
cond: { $eq: ["$$z.id", 12] },
},
},
},
},
{
$set: {
"statistic.crypt": {
$toDouble: {
$sum: [
{
$multiply: [{ $first: "$hh.col" }, 0.025],
},
"statistic.crypt",
],
},
},
},
},
{
$project: {
id_pr: 1,
id_server: 1,
role: 1,
warns: 1,
id_clan: 1,
statistic: 1,
design: 1,
date: 1,
inventory: 1,
voice: 1,
},
},)

How to mark an empty array as Null when Parsing data from Json Swift

So I have successfully managed to parse the JSON data shown below:
[
{
"IsRecentlyVerified": false,
"ID": 136888,
"UUID": "254B0B07-E7FC-4B4B-A37C-899BCB9D7261",
"DataProviderID": 18,
"DataProvidersReference": "0a9fdbb17feb6ccb7ec405cfb85222c4",
"OperatorID": 3,
"UsageTypeID": 1,
"AddressInfo": {
"ID": 137234,
"Title": "Ballee Road Park & Share",
"AddressLine1": "Ballee Road",
"Town": "Ballymena",
"Postcode": "BT42 2HD",
"CountryID": 1,
"Latitude": 54.844648,
"Longitude": -6.273606,
"AccessComments": "Ballee Road Park and Share, Ballymena",
"RelatedURL": "http://pod-point.com",
"Distance": 3.812940207797744,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 191571,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
},
{
"ID": 191572,
"ConnectionTypeID": 25,
"Reference": "2",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
}
],
"StatusTypeID": 0,
"DateLastStatusUpdate": "2020-02-21T15:15:00Z",
"MetadataValues": [
{
"ID": 6740,
"MetadataFieldID": 4,
"ItemValue": "Contains public sector information licensed under the Open Government Licence v2.0. http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2/"
}
],
"DataQualityLevel": 3,
"DateCreated": "2019-12-24T05:23:00Z",
"SubmissionStatusTypeID": 100
},
{
"IsRecentlyVerified": false,
"ID": 48636,
"UUID": "69C483E6-E271-4315-A56F-E3747EA59D52",
"DataProviderID": 1,
"OperatorID": 93,
"OperatorsReference": "SC99",
"UsageTypeID": 4,
"UsageCost": "Free",
"AddressInfo": {
"ID": 48982,
"Title": "Dunsilly Park and Ride, Dunsilly Roundabout",
"AddressLine1": "Dunsilly Park and Ride, Dunsilly Roundabout,",
"Town": "Antrim",
"Postcode": "BT41 2JH",
"CountryID": 1,
"Latitude": 54.74636,
"Longitude": -6.234244,
"Distance": 4.081140533868653,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 60091,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20,
"Quantity": 2
}
],
With the data struct file:
import Foundation
struct PublicCharger: Decodable {
let AddressInfo: AddressInfo
let Connections: [Connections]
}
struct AddressInfo: Decodable {
let Title: String
let Latitude: Double
let Longitude: Double
}
struct Connections: Decodable {
let StatusTypeID: Int
let ConnectionTypeID: Int
let PowerKW: Int
}
In my View Controller:
let decodedData = try decoder.decode([PublicCharger].self, from: data)
if !decodedData.isEmpty {
//print("Ran")
//print("Data: \(decodedData[0].AddressInfo.Title)")
let count = 0...10
for i in count {
publicChargerTitle.append(decodedData[i].AddressInfo.Title)
publicChargerLatitude.append(decodedData[i].AddressInfo.Latitude)
publicChargerLongitude.append(decodedData[i].AddressInfo.Longitude)
publicChargerStatus1.append(decodedData[i].Connections[0].StatusTypeID)
publicChargerStatus2.append(decodedData[i].Connections[1].StatusTypeID)
publicChargerConnector1.append(decodedData[i].Connections[0].ConnectionTypeID)
publicChargerConnector2.append(decodedData[i].Connections[1].ConnectionTypeID)
publicChargerKW1.append(decodedData[i].Connections[0].PowerKW)
publicChargerKW2.append(decodedData[i].Connections[1].PowerKW)
}
This works and adds the data to its own array.
The issue I'm seeing is not all chargers have the same number of connections. So when parsed the arrays are not matching each other at the end. Instead of skipping that array allocation with the next charger data, is there a way I can instead insert Null into the array to hold its place?
I have looked around and haven't yet found a clear solution to this issue. Any help would be greatly appreciated. API data from: https://api.openchargemap.io/
Thanks

I need to find least count by iterating child array and seperate as multiple arrays based on parent array in angular

myData = [
{
id: 'N5604-E',
areas: [
{
test_per_week: 154,
test_per_day: 22,
},
{
test_per_week: 154,
test_per_day: 52,
},
{
test_per_week: 154,
test_per_day: 32,
},
],
},
{
id: 'RSP4-E',
areas: [
{
test_per_week: 154,
test_per_day: 12,
},
{
test_per_week: 154,
test_per_day: 29,
},
],
},
];
I need to get minimum test_per_week in each area and need to store values in an array based on IDs
I have tried iterating using for loop and for each loop:
for (let i = 0; i < this.data.length; i++) {
this.chartProducts.push(this.data[i].id);
this.capacity[i].areas.forEach((element) => {
this.myData.push(element.test_per_day);
});
}
I stuck on how to calculate the min count of test_per_day for all areas in one ID.
This can be done using Array.map() combined with Math.min() as follows:
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
Please have a look at the runnable code snippet below.
const myData = [{
"id": "N5604-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 22 },
{ "test_per_week": 154, "test_per_day": 52 },
{ "test_per_week": 154, "test_per_day": 32 }
]
},
{
"id": "RSP4-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 12 },
{ "test_per_week": 154, "test_per_day": 29 }
]
}
];
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
console.log(result);
We used a map method for iterating and return a new array and reduce for comparing the values between together and finally using the min mathematical method to get the minimum number.
const result = myData.map((item) => {
const test_per_day = item.areas.reduce(
(max, val) => Math.min(max, val.test_per_day),
item.areas[0].test_per_day
);
return { id: item.id, test_per_day };
});
Result:
[
{
"id": "N5604-E",
"test_per_day": 22
},
{
"id": "RSP4-E",
"test_per_day": 12
}
]

Return an array of values obtained from calling reduce() of JS

I have a json array as follows
var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", Aage: 20, eAge:50},{id:"4",name:"D", sAge: 10, eAge:30}];
I want to take difference of sAge and eAge of each id and sum the final value if there are multiple diff values of same id. For that I have the following code
const ages = array.reduce((a, {id, sAge, eAge}) => (a[id] = (a[id] || 0) + eAge - sAge, a), {});
console.log(ages);
output of the above code snippet is as follows
{
"1": 20,
"2": 50,
"3": 20,
"4": 10
}
But If I want to obtain an array as follows after using reduce(), how can I achieve that?
[{id:"1",name:"A", hours:"20"},{id:"2",name:"B", hours:"50"},{id:"3",name:"C", hours:"20"},{id:"5",name:"D", hours:"10"}]
The following does the job but I didn't obtain your expected values
var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", sAge: 20, eAge:50},{id:"5",name:"D", sAge: 10, eAge:30}];
const ages = Object.values(arrayVal.reduce((a, {id, name, sAge, eAge}) => {
let difference = eAge - sAge;
if(a.hasOwnProperty(id)) {
a[id].hours+= difference;
} else {
a[id] = {
id:id,
name:name,
hours:difference
}
}
return a;
}, {}));
Output
[
{
"id": "1",
"name": "A",
"hours": 10
},
{
"id": "2",
"name": "B",
"hours": 40
},
{
"id": "3",
"name": "C",
"hours": 30
},
{
"id": "5",
"name": "D",
"hours": 20
}
]

Stacked Bar + Line chart angular library

Is there any angularjs library that can draw a chart with stacked bars + lines? Like this:
I'm looking for any library that supports this, with angular directives. I've found angular-nvd3-directives, that supports multicharts (combined chart types), but I don't think it supports bar stacking, only grouping.
I know that these questions are not well suited to SO, I'm looking for ANY, ONE, lib, not recommendations. (also it has to be free for commercial use)
The ZingChart-AngularJS directive exposes the entire ZingChart library, which supports mixed charts. It's free for commercial use. I made a demo on CodePen of what you're looking for.
Here's what your JS would look like:
var app = angular.module('myApp', ['zingchart-angularjs']);
app.controller('MainController', function($scope) {
$scope.myJson = {
"type": "mixed",
"background-color": "white",
"plot": {
"stacked": true
},
"series": [{
"type": "bar",
"values": [25, 30, 15, 20, 25],
"stack": 1,
"background-color": "#4372c1",
"hover-state": {
"visible": false
},
}, {
"type": "bar",
"values": [20, 10, 30, 25, 15],
"stack": 1,
"background-color": "#ea4204",
"hover-state": {
"visible": false
},
}, {
"type": "line",
"values": [25, 30, 15, 20, 25],
"line-color": "#38408c",
"marker": {
"background-color": "#38408c",
"border-color": "#38408c"
},
"hover-state": {
"visible": false
}
}, {
"type": "line",
"values": [25, 30, 15, 20, 25],
"line-color": "#38408c",
"marker": {
"background-color": "#38408c",
"border-color": "#38408c"
},
"hover-state": {
"visible": false
},
},]
};
});
angular-nvd3 supports this.
All you have to do is set bars1.stacked=true and bars2.stacked=true
http://plnkr.co/edit/2gSaYHgNkuNjbj9SGrWt?p=preview
$scope.options = {
chart: {
type: 'multiChart',
...
bars1: {stacked:true},
bars2: {stacked:true},
...
};
}
}

Resources