Average of Numbers in Javascript/Angularjs - javascript

I have a json response where have to calculate the average of "throughput_kbps" where protocol name is "TCP" for each result array.
I using Javascript/Angularjs for this
Please refer This json
Thanx in advance

You could do something like this:
var len1 = obj['flows'].length;
for (var i=0; i<len1; i++)
{
var tmp = obj.['flows'][i];
var len2 = tmp.['results'].length;
var mean = 0;
for (var j=0; j<len2; ++j)
{
var tmpResult = tmp.['results'][j];
if (tmpResult['protocol'] === 'TCP')
mean += tmpResult['throughput_kbps'];
}
console.log(mean);
}

Try this
var sum = 0;
var count = 0;
data.flows.map(function(d){
return d.results.filter(function(res){
if(res.protocol == 'TCP'){
sum += res.throughput_kbps;
count++;
return sum;
}
})
});
var avg = sum/count;

Pass your JSON as an argument to this function. This'll return you the average throughput you ask for.
function calculateThroughput(json){
var flowsObj = json.flows;
var throughputSum = 0;
var noOfSamples = 0;
for(noOfFlows in flowsObj){
var resultObj = flowsObj[noOfFlows].results;
for(noOfResults in resultObj){
if(resultObj[noOfResults].protocol == "TCP"){
throughputSum += resultObj[noOfResults].throughput_kbps;
noOfSamples++;
}
}
}
return (throughputSum/noOfSamples);
};
Hope this helps.

Related

JavaScript Cosine similarity function

I am trying to create a cosine similarity function and then display the results in a HTML element. I have written the following:
function cosinesim(A,B){
var dotproduct=0;
var mA=0;
var mB=0;
for(i = 0; i < A.length;){
dotproduct += (A[i] * B[i]);
mA += (A[i]*A[i]);
mB += (B[i]*B[i]);
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
var similarity = (dotproduct)/(mA)*(mB)
return similarity;
}
//.....
var array1 = [1,0,0,1];
var array2 = [1,0,0,0];
var p = cosinesim(array1,array2);
document.getElementById("sim").innerHTML = String(p);
I have tested and both the arrays I am inputting are the same length, however when my code runs to this bit it crashes and I cant seem to find what is wrong.
Any help is appreciated, thanks.
function cosinesim(A,B){
var dotproduct=0;
var mA=0;
var mB=0;
for(i = 0; i < A.length; i++){ // here you missed the i++
dotproduct += (A[i] * B[i]);
mA += (A[i]*A[i]);
mB += (B[i]*B[i]);
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
var similarity = (dotproduct)/((mA)*(mB)) // here you needed extra brackets
return similarity;
}
var array1 = [1,0,0,1];
var array2 = [1,0,0,0];
var p = cosinesim(array1,array2);
console.log(p);
This should give the actual cosine similarity.
You were missing: 1.) The i++ in your loop, as mentioned before. 2.) Extra brackets around (mA)*(mB) in this line: var similarity = (dotproduct)/((mA)*(mB)) -> otherwise the division is done before the multiplication.
you missed i++ in your loop which leads to an endless one
replacing for(i = 0; i < A.length;) to for(i = 0; i < A.length;i++) fixed the issue
Using the map and reduce the functionality of javascript
function dotp(x, y) {
function dotp_sum(a, b) {
return a + b;
}
function dotp_times(a, i) {
return x[i] * y[i];
}
return x.map(dotp_times).reduce(dotp_sum, 0);
}
function cosineSimilarity(A,B){
var similarity = dotp(A, B) / (Math.sqrt(dotp(A,A)) * Math.sqrt(dotp(B,B)));
return similarity;
}
var array1 = [1,2,2,1];
var array2 = [1,3,2,0];
var p = cosineSimilarity(array1,array2);
console.log(p);
Hope this helps!! Happy coding!!
function cosinesim(A,B){
var dotproduct=0;
var mA=0;
var mB=0;
for(i = 0; i < A.length; i++){
dotproduct += (A[i] * B[i]);
mA += (A[i]*A[i]);
mB += (B[i]*B[i]);
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
var similarity = (dotproduct)/(mA)*(mB)
return similarity;
}
var array1 = [1,0,0,1];
var array2 = [1,0,0,0];
var p = cosinesim(array1,array2);
console.log(p);

Javascript to generate dynamic string of numbers

I have a requirement to write a function to generate the below dynamic string.
Here are some examples of what the output should look like for a function argument of 6, 5, and 4, respectively (Actually I am flexible with passing the argument).
123456789112345678921234567893123456789412345678951234567896
12345678911234567892123456789312345678941234567895
1234567891123456789212345678931234567894
The length of the output will always be a multiple of 10.
Should I use normal JS arrays OR can I use some ready jQuery methods to acheive this ?
Here is the code, I think it will help you
function dynamicNumber(n){
var s="";
for(i=1;i<=n;i++){
s=s+"123456789"+i;
}
return s;
}
Try something like this.
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
Example below:
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
console.log(generateString(6))
console.log(generateString(5))
console.log(generateString(4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is how I do it:
function dynamic_string(val){
var strin = "123456789"
var result = ""
for(var i = 1; i <= val; i++){
result += strin;
result += i;
}
console.log(result)
}
dynamic_string(6)
What about (ES6):
function getString(amount) {
let sNumber = '';
for(let i=1;i<=amount;i++) {
sNumber += '123456789' + i;
}
return sNumber;
}
Try this way
var nu=5;
for(var i=1;i<=nu;i++){
for(j=1;j<=9;j++){
console.log(j)
}
console.log(i)
}
jsbin
You can use this simple logic...
var str = '123456789';
var len=5;
var out = ''
for(var i=1;i<=len;i++){out+=str+i;}
console.log(out)

javascript search in array elements

I have array like this:
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
And I have
var search_date="17/2/2008";
I want to find last occurence of note and user for that note. Anyone knows how? Thanks in advance for your reply.
Try this:
var highestIndex = 0;
for (var i = 0; i < notes.length; i++){
if (notes[i].indexOf(search_date) != -1){
highestIndex = i;
}
}
//after for loop, highestIndex contains the last index containing the search date.
Then to get the user, you can parse like this:
var user = notes[highestIndex].substring(0, notes[highestIndex].indexOf(',') - 1);
You can iterate the array and check the attribute
or
you can user underscore.js: http://underscorejs.org/#filter
for (var i = 0; i < notes; i++) {
if (notes[i].indexOf(search_date) != -1) {
// notes [i] contain your date
}
}
var match = JSON.stringify(notes).match("\"([^,]*),date\:"+search_date+",note\:([^,]*)\"");
alert(match[1]);
alert(match[2]);
works ;-)
Something like this:
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
var search_date="17/2/2008";
var res = [];
for(var i = 0; i < notes.length; i++) {
var note = notes[i];
if(note.indexOf(search_date) !== -1) {
res.push(note.substring(note.indexOf('note:') + 1), note.length);
}
}
var noteYouWanted = res[res.length - 1];
For the last occurrence and if performance matters:
var notes = ['user1,date:13/2/2008,note:blablabla', 'user1,date:15/2/2008,note:blablabla', 'user1,date:17/2/2008,note:blablabla', 'user1,date:13/3/2008,note:blablabla'],
search = '17/2/2008',
notesLength = notes.length - 1,
counter,
highestIndex = null;
for (counter = notesLength; counter >= 0; counter--) {
if (notes[counter].indexOf(search) !== -1) {
highestIndex = counter;
break;
}
}
// do something with notes[highestIndex]
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
var search_date="17/2/2008";
var user, note;
$.each(notes, function(i) {
var search = new RegExp('\\b' + search_date + '\\b','i');
// if search term is found
if (notes[i].match(search)) {
var arr = notes[i].split(',');
user = arr[0];
note = arr[2].substr(5);
}
}); // end loop
console.log(user);
console.log(note);
example here: http://jsfiddle.net/Misiu/Wn7Rw/

Getting a nth element from a string

How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {

Why won't my inputs value sum?

Im trying to do a sum of values i get from id but it keeps appending second value to first instead of doing sum as it should.
Example 23+25=2325
Heres my code:
This is the code im using to sum.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
Try this:
var one = parseInt(document.getElementById("veb_blocos-"+i).value, 10);
var two = parseInt(document.getElementById("veb_pellet-"+i).value, 10);
Because the value of an input is a string. Cast it to int.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = parseInt(one,10)+parseInt(two,10);
document.getElementById("total1-"+i).value = sum1;
};
});
Here is the safest possible solution (presuming the requested DOM nodes are present):
$('input').blur(function () {
var i = 0,
one = 0,
two = 0;
for (i = 1; i <= value; i += 1) {
one = Number(document.getElementById("veb_blocos-" + i).value);
two = Number(document.getElementById("veb_pellet-" + i).value);
if (isNaN(one)) {
one = 0;
}
if (isNaN(two)) {
two = 0;
}
document.getElementById("total1-" + i).value = one + two;
};
});
Try:
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseInt(document.getElementById("veb_blocos-"+i).value);
var two = parseInt(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
It's because your values are string datatypes instead of a number type. You'll need to parse them first.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseFloat(document.getElementById("veb_blocos-"+i).value);
var two = parseFloat(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});

Categories