Counting from deferent function for() - javascript

i have some problem with this work, i plan to create a function to compute from two for () functions. if you ask why I have to make 2 functions to calculate it, it is because the calculated data is taken from different json data, and I need to loops each of those data to get dynamic sum row.
my first function for()
jml_lls_doktor = [
{
"t20181": {
"jum": 5090 //get it jum
}
},
{
"t20191": {
"jum": 3386
}
},
{
"t20201": {
"jum": 1826
}
}
];
let result_doktor = [];
let i = 0;
if(jml_lls_doktor){
for(var key in jml_lls_doktor){
result_doktor[i]={
"jumlah_doktor_hitung" : Object.keys(jml_lls_doktor[key]).map((keys, i9)=>
jml_lls_doktor[key][keys]
)
}
i++;
}
}
console.log(result_doktor);
and this my second function for
let jml_ipk3 = [
{
"2018": {
"ipk2": "null",
"ipk3": "null"
}
},
{
"2019": {
"ipk2": 4,
"ipk3": 4
}
},
{
"2020": {
"ipk2": "null",
"ipk3": "null"
}
}
];
let result_ipk3 = [];
let i2 = 0;
if(jml_ipk3){
for(var key in jml_ipk3){
result_ipk3[i2]={
"ipk3" : Object.keys(jml_ipk3[key]).map((keys, i9)=>
jml_ipk3[key][keys].ipk3
)
}
i2++;
}
}
console.log(result_ipk3);
How i count
(result_ipk3/result_doktor)*100

let count = [];
let i = 0;
for(var key in jml_lls_doktor, jml_ipk3 ){
count [i]={
"ipk3" : Object.keys(jml_lls_doktor[key]).map((keys, i9)=>
parseInt(jml_lls_doktor[key][keys].ipk3)
),
"aktif" : Object.keys(jml_lls_doktor_aktif[key]).map((keys, i9)=>
parseInt(jml_lls_doktor_aktif[key][keys].jum)
)
}
i_count_doktor++;
}
///On rendering reactjs
{
count_doktor.map((list,i)=>
<td style={{textAlign:'center'}}>
{String(list.ipk3/list.aktif*100).slice(0,4)}%
</td>
)
}

Related

Filter multiple values with multiple attributes js

I want to filter the multiple attributes with multiple values
'arr' is a list of all products and f_... is the attribute like color or type.
'namet' is the chosen attribute from the user.
'keyt' is the values of each attribute like red, yellow and green.
let arr = [
{ "id": 523, "f_105": ["992","996"], "f_104": ["985"], "f_106":["1000"] },
{ "id": 524, "f_105": ["993","996"], "f_104": ["984"], "f_106":["1001"] }
]
these arrays which user chose for searching
I can get the attrubites like this
var namet = ['f_106', 'f_106', 'f_105', 'f_105', 'f_104' ];
var keyt = ['1000' , '1001', '993', '996', '985'];
OR
var chooenKey = ['f_106', 'f_105', 'f_104']
var chosenAttr = {
"f_106": ["1000", "1001"],
"f_105": ["993", "996"],
"f_104": ["985"],
}
OR
var chosenAttr =
[
{"f_106": ["1000", "1001"]},
{"f_105": ["993", "996"]},
{"f_104": ["985"]}
]
I want a method to loop to get result like variable 'filtered'
var filtered = d =>
(d.f_106.indexOf("1000") > -1 || d.f_106.indexOf("1001") > -1) &&
(d.f_105.indexOf("993") > -1 || d.f_105.indexOf("996") > -1) &&
(d.f_104.indexOf("985") > -1)
then put it here
const f = arr.filter(filtered);
You can also give another type to filter the product with multiple attributes.
If you examine the example I sent, I believe it will solve your problem.
let arr = [
{ "id": 523, "f_105": ["992", "996"], "f_104": ["985"], "f_106": ["1000"] },
{ "id": 524, "f_105": ["993", "996"], "f_104": ["984"], "f_106": ["1001"] }
]
var chosenAttr =
[
{ "f_106": ["1000", "1001"] },
{ "f_105": ["992"] },
{ "f_104": ["985"] }
]
function filterArr() {
var arrCopy = arr;
for (i = 0; i < chosenAttr.length; i++) {
for (var key in chosenAttr[i]) {
arrCopy = arrCopy.filter(function (item) {
var is_match = false;
for (var idx in chosenAttr[i][key]) {
let val = chosenAttr[i][key][idx];
if (item[key].indexOf(val) > -1) {
is_match = true;
}
}
return is_match;
});
}
}
return arrCopy;
}
var filterData = filterArr();
$('#response').html(JSON.stringify(filterData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
<code id="response">
</code>
</pre>

How can find the sum and count of json data in javascript

Hi iam trying to group my json data in to sub json data.
here is my json data
[
{
"STATUS":"ACTIVE",
"AMOUNT":200,
"pENDING":100,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":100,
"pENDING":30,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":150,
"pENDING":10,
}
]
and my expected result like
[
{
"STATUS":"ACTIVE",
"COUNT":"1",
"TOTAL AMOUNT":200,
"TOTAL PENDING":100
},
{
"STATUS":"NOTACTIVE",
"COUNT":"2",
"TOTAL AMOUNT":250,
"TOTAL PENDING":40
}
]
I want the separate count ,sum of amount,sum of pending for each status
Could you please help me to find the result
You can do it like this
Idea to handle such things.
so here i am looping through the array and checking for status in the output object. if the status is already in output object i will update the required values. if it's not there than i will create a new one in output object.
let arr =[
{
"STATUS":"ACTIVE",
"AMOUNT":200,
"PENDING":100,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":100,
"PENDING":30,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":150,
"PENDING":10,
}
];
let output = arr.reduce((op,cur)=>{
if(op[cur['STATUS']]){
op[cur['STATUS']]['TOTAL_AMOUNT']+=cur['AMOUNT'];
op[cur['STATUS']]['TOTAL_PENDING']+=cur['PENDING'];
op[cur['STATUS']]['COUNT']++;
} else {
op[cur['STATUS']] ={
'COUNT' : 1,
'TOTAL_AMOUNT' : cur['AMOUNT'],
'TOTAL_PENDING' : cur['PENDING'],
}
}
return op;
},{})
console.log(output);
Trying to fix your own method I would suggest something like this. I tried to do it generic in case you would find it more useful, although this solution would have a problem if the AMOUNT or PENDING entries are not numeric.
const IDENTIFIER = 'STATUS'
const result= {};
data.forEach( entry => {
// Check is this status exists, if not, create one
if(!result[entry[IDENTIFIER]]){
result[entry[IDENTIFIER]] = {}
}
// For each item in the entry add the value
Object.keys(entry).forEach( item => {
// Only sum the items that are not the identifier
if(item !== IDENTIFIER){
result[entry[IDENTIFIER]][item] = (result[entry[IDENTIFIER]][item] || 0) + entry[item];
}
})
});
Hope you find this useful
Try this my friend!
var json = [{
"STATUS":"ACTIVE",
"AMOUNT":200,
"pENDING":100,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":100,
"pENDING":30,
},
{
"STATUS":"NOTACTIVE",
"AMOUNT":150,
"pENDING":10,
}];
var result = [];
var totalActive = 0;
var amountActive = 0;
var pendingActive = 0;
var totalNotActive = 0;
var pendingNotActive= 0;
var amountNotActive = 0;
for(var i=0; i < json.length; i++){
var item = json[i];
if (item.STATUS.toString() == "ACTIVE"){
totalActive +=1;
amountActive = amountActive + item.AMOUNT;
pendingActive = pendingActive + item.pENDING;
}
else
{
totalNotActive +=1;
amountNotActive = amountNotActive + item.AMOUNT;
pendingNotActive = pendingNotActive + item.pENDING;
}
}
result.push({ "STATUS" : "ACTIVE" , "COUNT" : totalActive.toString(), "AMOUNT" : amountActive.toString(), "pENDING" : pendingActive.toString() })
result.push({ "STATUS" : "NOTACTIVE" , "COUNT" : totalNotActive.toString(), "AMOUNT" : amountNotActive.toString(), "pENDING" : pendingNotActive.toString() })
console.log(result);

javascript - modify my json [duplicate]

This question already has answers here:
Traverse all the Nodes of a JSON Object Tree with JavaScript
(17 answers)
Closed 6 years ago.
I have a json object I would like to modify. This is data:
var data1 = {
"a#1.0.3": {
"b#2.3.0": {
"c#2.0.0": {
"d#0.4.0": {
"e#1.1.1": {}
},
"f#0.5.3": {}
},
"j#2.15.2": {
"x#1.2.3": {}
}
},
"i#1.5.8": {}
}
};
basically for every key, a the left of '#' I want to add char + sum of every number on the right and on the right replace all '.' with '-'. For example, if key is 'abcd#1.12.4', my new key will be 'abcd17#1-12-4'.
for this example I want this as result:
var data2 = {
"a4#1-0-3": {
"b5#2-3-0": {
"c2#2-0-0": {
"d4#0-4-0": {
"e3#1-1-1": {}
},
"f8#0-5-3": {}
},
"j19#2-15-2": {
"x6#1-2-3": {}
}
},
"i14#1-5-8": {}
}
};
can you please help ?
Here is a working fiddle. The code is:
var data1 = {
"a#1.0.3": {
"b#2.3.0": {
"c#2.0.0": {
"d#0.4.0": {
"e#1.1.1": {}
},
"f#0.5.3": {}
},
"j#2.15.2": {
"x#1.2.3": {}
}
},
"i#1.5.8": {}
}
};
console.log(JSON.stringify(fixData(data1)));
function fixData(data) {
var result = {};
for (var key in data) {
if (data.hasOwnProperty(key)) {
if (key.indexOf("#") == -1)
continue; // Ignore keys without #'s
var parts = key.split("#");
var left = parts[0];
var right = parts[1];
// Replace .'s with -'s
while (right.indexOf(".") > -1) {
right = right.replace(".", "-");
}
// Add up values
var num = 0;
var splits = right.split("-");
for (var i = 0; i < splits.length; i++) {
var chars = splits[i];
if (!isNaN(chars)) {
num += parseInt(chars);
}
}
left += num;
// Replace key
var existing = data[key];
result[left+"#"+right] = fixData(existing);
}
}
return result;
}
This gives:
{
"a4#1-0-3":{
"b5#2-3-0":{
"c2#2-0-0":{
"d4#0-4-0":{
"e3#1-1-1":{
}
},
"f8#0-5-3":{
}
},
"j19#2-15-2":{
"x6#1-2-3":{
}
}
},
"i14#1-5-8":{
}
}
}

How to get the array number with the name value in javascript

This is the json I'm trying to for loop through:
var json = {"series":[
{
"id":1448822,
"name":"Buckinghamshire",
"selected":true,
"data":[
[
19.23,
19.23
]
]
},
{
"id":1448823,
"name":"Cambridgeshire",
"selected":false,
"data":[
[
38.46,
61.54
]
]
}
}
I've been trying to workout how to get the array position with the name selected with value true to the following code:
for (var i = 0; i < json.length; i++) {
var geoAreaSelected = serData[i].selected;
if (geoAreaSelected === true) {
this.series[i].data[i].setState('select');
}
};
EDIT:
var json = {
"series":[
{
"id":1448822,
"name":"Buckinghamshire",
"selected":true,
"data":[[19.23, 19.23]]
},
{
"id":1448823,
"name":"Cambridgeshire",
"selected":false,
"data":[[38.46, 61.54]]
}
] // <= This was missing
};
for (var i = 0; i < json.series.length; i++) {
var geoAreaSelected = json.series[i].selected;
if (geoAreaSelected === true) {
console.log( json.series[i].data[i])
}
};
Console logs [ 19.23, 19.23 ]
You have to iterate over json.series and not over json
for (var i = 0; i < json.series.length; i++) {
var geoAreaSelected = json.series[i].selected;
if (geoAreaSelected === true) {
json.series[i].data[i].setState('select');
console.log(i); // <--- you can use the variable i to access ith object in the array
}
};

pairing object items together with a loop

I have the following data and I am wondering how I can match up email1 to password1 and email2 to password2 in this format email:password. I can do it if I do object[0] +":"+ object[1] and object[2] +":"+ object[3] but when the object gets populated with 10 or more items this method is not very efficient. How can I do this with a loop?
I'm using the following code to create the structure:
$("#accounts").on("submit", function(event) {
event.preventDefault();
var form = $(this).serializeArray();
});
You can change the increment in a for loop. Try:
var results = [];
For(var i = 0; i < vals.length; i += 2) {
results.push( { vals[i].value: vals[i+1].value });
}
You can try increment your loop step.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#for_Statement
Code:
var testMe=new Array({"name":"em1"},{"pwd":"pwd1"},{"name":"em2"},{"pwd":"em2"});
console.log(testMe)
for (var i = 0; i < testMe.length; i+=2) {
console.log(testMe[i].name+"-->"+testMe[i+1].pwd)
}
Demo: http://jsfiddle.net/IrvinDominin/qbVwH/
//
Array.prototype.e = Array.prototype.forEach;
function pair( arr ) {
var len = arr.length;
if ( len ) {
do {
arr.push( arr.splice( 0, 2 ) );
} while ( ( len -= 2 ) >= 2 );
}
return arr;
};
var yourData = [
{ name:"email1", value:"321" },
{ name:"pw1", value:"123" },
{ name:"email2", value:"qwe" },
{ name:"pw2", value:"ewq" },
{ name:"email3", value:"234" },
{ name:"pw3", value:"432" }
],
pairs = {};
pair( yourData )
.e(
function ( P ) {
pairs[ P[0].name ] = P[1].name;
}
);
console.log( pairs );
// Object { email1="pw1", email2="pw2", email3="pw4"}
//

Categories

Resources