Created
May 22, 2016 11:23
-
-
Save sadick254/3974f92a36c0cff4953b56f0452f25ea to your computer and use it in GitHub Desktop.
Calculating mean
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mean(obj) | |
{ | |
var props = getProps(obj); | |
var means = []; | |
function findMean(item){ | |
var found = -1; | |
for (var i = means.length - 1; i >= 0; i--) { | |
if(means[i].prop === item){ | |
found = i; | |
} | |
} | |
return found; | |
} | |
var frequencies = getFrequency(obj); | |
for (var i = frequencies.length - 1; i >= 0; i--) { | |
if(typeof frequencies[i].val === 'number'){ | |
var foundMean = findMean(frequencies[i].prop); | |
if(foundMean===-1){ | |
means.push({prop:frequencies[i].prop,count:frequencies[i].frequency,sum:frequencies[i].val,mean:frequencies[i].val}); | |
} else { | |
means[foundMean].count+=frequencies[i].frequency; | |
means[foundMean].sum+=(frequencies[i].val * frequencies[i].frequency); | |
means[foundMean].mean = means[foundMean].sum /means[foundMean].count; | |
} | |
} | |
} | |
return means; | |
} | |
function getFrequency(obj){ | |
var size = obj.length; | |
var items = []; | |
var props = getProps(obj); | |
function findItem(itemSearched){ | |
var found = -1; | |
for (var i = 0; i<items.length;i++) { | |
if(items[i].prop == itemSearched.prop && items[i].val == itemSearched.val) | |
{ | |
found = i; | |
} | |
} | |
return found; | |
} | |
for(var i = 0; i<props.length;i++) | |
{ | |
for(var j=0; j<size;j++) | |
{ | |
var item = {prop:props[i].prop,val:obj[j][props[i].prop],frequency:1}; | |
var foundItem = findItem(item); | |
if(foundItem ===-1){ | |
items.push(item); | |
} else { | |
items[foundItem].frequency+=1 | |
} | |
} | |
} | |
return items; | |
} | |
function getProps(obj){ | |
var size = obj.length; | |
var props = []; | |
function findProp(property,type) | |
{ | |
var found = false; | |
props.forEach(function(prop){ | |
if(prop.prop==property && prop.type==type){ | |
found = true; | |
} | |
}) | |
return found; | |
} | |
for(var i=0;i<size;i++){ | |
if(typeof obj[i] === 'object'){ | |
Object.keys(obj[i]).forEach(function(prop){ | |
var valueType = typeof obj[i][prop]; | |
if(!findProp(prop,valueType)){ | |
props.push({prop:prop,type:valueType}); | |
} | |
}); | |
} | |
} | |
return props; | |
} | |
//example : | |
var ages = [{age:12},{age:13},{age:20},{17}]; | |
console.log(ages); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment