Get count of values in json data and create variable based on those for c3 table - angularjs

I am trying to create a dynamic donut chart as I don’t know how many variables will be coming in but the dataset will be in the 10,000's with between 1 and 20 variables.
I have got my data into an array as below.
How do I create a var for each unique element in the array and its count i.e var 1 = [sys1, 94] or similer so they can be used in the columns and colours config
Original data
res.data[{system:'sys1'},
{system:'sys1'},
{system:'sys2'},
{system:'sys1'},
{system:'sys3'},
{system:'sys3'}]
Getting keys
var array_elements = []
angular.forEach(res.data, function(value, key){
if (array_elements.indexOf(value.system) === -1){
array_elements.push(value.system)
}
})
array_elements = ["sys1", "sys2", "sys3"];
config
var donutData = {
type : 'donut',
colors: {
Cats: $.pfPaletteColors.blue,
Hamsters: $.pfPaletteColors.green,
Fish: $.pfPaletteColors.orange,
Dogs: $.pfPaletteColors.red
},
columns: [
['Dogs', 2],
['Cats', 2],
['Fish', 3],
['Hamsters', 1]
],

You can do something like this:
var data = [{
system: 'sys1'
}, {
system: 'sys1'
}, {
system: 'sys2'
}, {
system: 'sys1'
}, {
system: 'sys3'
}, {
system: 'sys3'
}];
var tmp = {};
data.forEach(function(x) {
tmp[x.system] = (tmp[x.system] || 0) + 1;
});
var keys = Object.keys(graphData);
var finalData = [];
for(var i = 0; i < keys.length; i++) {
var x = [];
x.push(keys[i]);
x.push(graphData[keys[i]]);
finalData.push(x);
}
console.log(finalData);
Fiddle example

Related

Creating and pushing elements in an new array depends on conditions

My Data Array
data:[
0:{
id:1 ,.....
competetion:[
0:{
id: 1....,
match:[
0:{id: 1 ......},
1:{same}
.
.
]
1:{same}]},
2:{same}
.
.
]
},
1:{same},
2:{same}
.
.
.
]
For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...
My Code: Here i am looping it:
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
this.sportarr.push({ // I declared a new array where i want to push the element
id: i,
value: false
});
}
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map
const arrlength = data.length;
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = data[i].competetion.map( (val, index) => {
#write your own logic to produce the required outcome
return {
id: index,
value: false
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = response.data[i].competetion.map((val, index) => {
let match = [];
match = val.match.map((value, indx) => {
return {
id: indx,
value: false
};
});
return {
id: index,
value: false,
match
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
}
Now i am getting what i wanted
i am not sure if you are trying to create an array for each nasted array (competetion and match) or not, but here you go
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const competetionList = // Array of competetions
[].concat.apply([], this.sportsSidebar.map(item => item.competetion));
const matchList = // Array of matchs
[].concat.apply([], competetionList .map(item => item.match));
}

Matching two array key and combine it's value with google app script

I have two formatted array as below code, and I would like to match the id and get the matched id value of size and stock
I have the code from github as below but can not get it to work
var arraysize = [];
var arraycode = [];
var code = '{id:'+stock[i][1] +',stock:'+ stock[i][4]+'}';
var size = '{id:'+tomatchcode+',size:'+tomatchsize+'}';
arraycode[i] = code;
arraysize[i] = size;
Logger.log(arraysize);
Logger.log(arraycode);
[19-08-29 10:32:35:003 ICT] [{id:59,size:36}, {id:123,size:37}, {id:62,size:38}, {id:63,size:39}, {id:64,size:40}]
[19-08-29 10:32:35:003 ICT] [{id:63,stock:17}, {id:123,stock:16}, {id:59,stock:10}, {id:64,stock:12}, {id:62,stock:14}]
//both array id value in random position but have same value
var matcharray =checkArrayForMatches(arraycode,arraysize)
function checkArrayForMatches(array,properties){
var returnArray = [];
if (Array.isArray(array[0])){
for (var i = 0,x = array.length;i<x;i++){
var row = array[i];
var match = true;
for (var j in properties){
if (properties[j] !== row[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
} else if (typeof array[0] == 'object'){
for (var i = 0,x = array.length;i<x;i++){
var obj = array[i];
var match = true;
for (var j in properties){
if (obj[j] !== properties[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
}
return returnArray;
}
The above function not returning any value. I would like it to returning array like this which contain size value following by stock value [{36,10}, {37,16}, {38,13}, {39,17}, {40,12}]
As you can see each returned value have a matching id.
Any help is much appreciated.
Flow:
Create a hashtable of id:stock
Use Array.map to retrieve stock from hash table using id of arraysize
Snippet:
var arraysize = [{ id: 59, size: 36}, { id: 123, size: 37}, { id: 62, size: 38}, { id: 63, size: 39}, { id: 64, size: 40}];
var arraycode = [{ id: 63, stock: 17}, { id: 123, stock: 16}, { id: 59, stock: 10}, { id: 64, stock: 12}, { id: 62, stock: 13}];
var arrayCodeObj = {};
arraycode.forEach(function(obj){arrayCodeObj[obj.id]=obj.stock});//create hash table
var arr2d = arraysize.map(function(obj){ return [obj.size, arrayCodeObj[obj.id]]})
console.log(arr2d)
console.log(arrayCodeObj)

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

how to fill <array> struct by another struct

My app in Xcode with swift language programming :
I have a struct like:
struct PageFilter {
var key: Int?
var title: NSString?
}
And then I have the values in:
filters are coming from API and i am saving them to extractedFilter
if let filters = filters {
for filter in filters {
var extractedFilter = PageFilter()
extractedFilter.key = filter["key"].integerValue
extractedFilter.title = filter["title"].stringValue
}
}
I have an array of page filter like :
lazy var availableFilters = Array<PageFilter>()
I want to fill the availableFilters with ExtractedFilter.
******* *i fixed the issue by a loop like this code :
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}
thanks to all*
The following Swift 1.2 playground code would do it - I have put in a function to simulate the call to the API
//: Playground - noun: a place where people can play
import Cocoa
struct PageFilter {
var key: Int?
var title: NSString?
}
// this would be replaced by whatever way you get your filters from the API
func getFiltersFromApi() -> [PageFilter]? {
// return nil // uncomment this line to demo the API returning nothing
return [PageFilter(key: 1, title: "one"),
PageFilter(key: 2, title: "two"),
PageFilter(key: 3, title: "three"),
PageFilter(key: nil, title: nil)
]
}
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
let extractedFilters: [PageFilter]
if let filters = filters {
extractedFilters = filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
extractedFilters = []
}
for filter in extractedFilters {
println("key: \(filter.key), title: \(filter.title)")
}
Alternatively you could have your lazy var like this
var availableFilters: [PageFilter] = {
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
if let filters = filters {
return filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
return []
}
}()
The code is similar to Leonardo's answer, the main difference being the use of the map function instead of for ... in ...
Try like this:
struct PageFilter {
var key = Int()
var title = String()
}
var filters:[PageFilter]? = []
filters = [PageFilter(key: 1, title: "one"), PageFilter(key: 2, title: "two"), PageFilter(key: 3, title: "three")]
var extractedFilter = Array<PageFilter>()
if let filters = filters {
for filter in filters {
extractedFilter.append(PageFilter(key: filter.key, title: filter.title))
}
}
println(extractedFilter[1].key) // "2"
println(extractedFilter[1].title) // "two"
I fixed the issue by a loop like this:
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}

How do I get my Filters from Filtersfeature

I am using FiltersFeature:
this.features = {
ftype: 'filters',
encode: false,
local: true
};
I would like to access my current filters on my table. Ie. not the filter configuration object, but what the changes user has done to the table (I want to save this in the database).
There is a filters object on grid, but that just gives me the filter configuration from all the columns.
handler: function (btn) {
var grid = btn.up('grid');
grid.filters
}
I need the actual values. I'm looking for something like this:
var v = {
filter: {
column: 'name',
value: 'bob'
},
filter: {
column: 'date',
value1: '11.11.11',
value2: '12.12.12'
}
}
Anyone know where i can get this info?
The answer I found out was to use this method :)
myTableGrid.filters.getFilterData()
I get something like this :
v = [{
"field": "myColumn1",
"data": {
"type": "string",
"value": "anna"}
}, {
"field": "myColumn2_fixedvalue",
"data": {
"type": "list",
"value": [60]}
}]
Filter does not contain any values.
You should parse actual values from the grid.
var columnTitle = [];
var fieldName = [];
var data = [];
var visibleColumns = grid.query('gridcolumn:not([hidden])');
visibleColumns.forEach(function(c) {
columnTitle.push(c.text);
fieldName.push(c.dataIndex);
});
for (rowIndex = 0; rowIndex < grid.store.getCount(); rowIndex++) {
var row = grid.getView().getRow(rowIndex);
var fieldValues = Ext.fly(row).query('div.x-grid-cell-inner');
var map = {}
for (colIndex = 0; colIndex < fieldName.length; colIndex++) {
map[fieldName[colIndex]] = fieldValues[colIndex].textContent;
}
data.push(map);
}
As a result, you will get an array of objects, something like
[{"user.login":"iivanov","email":"ivanov#mail.com"},{"user.login":"ppetrov","email":"petrov#mail.com"},{"user.login":"plosev","email":"elk#gmail.com"}]

Resources