JS how to Sum/Average? - javascript

I have an object and need to sum/average of each dynamic span. Can't seem to convert those to numbers though. Please Help.
Console Log
Code Sample
Expand/Collapse Created : 1/3/2017 ‎<span>(10)‎</span>
Expand/Collapse Created : 1/4/2017 ‎<span>(38)‎</span>
Expand/Collapse Created : 1/5/2017 ‎‎<span>(13)</span>
Expand/Collapse Created : 1/6/2017 ‎‎<span>(35)</span>
Expand/Collapse Created : 1/9/2017 ‎‎<span>(46)</span>
Expand/Collapse Created : 1/10/2017 ‎‎<span>(17)</span>
Expand/Collapse Created : 1/11/2017 ‎‎<span>(27)</span>
var arr = [];
$(".ms-gb span").each(function(index, elem){
arr.push($(this).text());
});
$("#result").text(arr.join("+")); // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
var allNumbers = document.getElementById('result').innerText; // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
allNumbers = allNumbers.replace(/["'()]/g,""); // ‎‎10+‎38+‎13+‎35+‎46+‎17+‎28
var newString = allNumbers.split("+"); // Object - ["‎10", "‎38", "‎13", "‎35", "‎46", "‎17", "‎27"]

well you're pretty close. i'd recommend using the reduce function
var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)
the plus signs in front of a and b might look weird, but its a quick way to coerce a string into a number in javascript

You can strip out non-numeric characters, parse each number, and then perform the addition within the loop.
// variables
var sum = 0;
var average = 0;
var numOfSpan = $('span').length;
// each span loop
$('span').each(function(key, val){
// add the value of the span to the sum var
sum+= parseInt($(this).text().replace(/\D/g,''));
// on the last itteration ...
if(key == (numOfSpan - 1)) {
// calulate average
average = sum / numOfSpan;
// log sum and average
console.log('sum = ' + sum);
console.log('average = ' + average);
}
});
<span>(10)</span>
‎<span>(38)</span>
<span>(13)</span>
<span>(35)</span>
‎<span>(46)</span>
‎‎<span>(17)</span>
<span>(27)</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You have to iterate your array and then change every string to number. After that you can add every elements to itself.
var a = 0;
for(var i=0;i<newString.length;i++) {
a += parseInt(newString[i]);}
And then a will be the sum

Related

How to split String, convert to Numbers and Sum

I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);

Accessing indexes of a string inside an array and taking the sum

Ok so I am trying to access each individual number in the strings inside of this array.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
str = array[i];
}
The problem is that this is the output: '999-992-1313'
and not the first element array[0]: '818-625-9945'
When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
console.log(array[i][j]);
}
}
I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
if (array[i](j).indexOf('8') !== -1) {
// add one to total score
// then find a way to increase the index to the next index (might need help here also please)
}
}
}
Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split().
This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned.
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.reduce(function (r, a) {
return r + a.split('').filter(function (b) { return b === '8'; }).length;
}, 0);
document.write('Score: ' + score);
A suggested approach with counting all '8' on every string:
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.map(function (a) {
return a.split('').filter(function (b) { return b === '8'; }).length;
});
document.write('Score: ' + score);
Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array)
This you could easily do with:
'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];
function getHighestEightCountFromArray(arr) {
var max = 0,
result = {};
if (arr && arr.forEach) {
arr.forEach(function(value, idx) {
var cnt = value.split('8').length;
if (max < cnt) {
// found more nr 8 in this section (nl: cnt - 1)
max = cnt;
// store the value that gave this max
result = {
count: cnt - 1,
value: value,
index: idx
};
}
});
}
return result;
}
console.log(getHighestEightCountFromArray(array));
The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum"
should be preferred(first one in the array, or the newest / latest one in the array)
OLD
I'm not sure which sums you are missing, but you could do it in the following way.
There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together.
There are definitelly shorter ways, but this is a way how you could do it
'use strict';
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
sumPerIndex = [],
totalSum = 0;
array.forEach(function(item, idx) {
var values = item.split('-'), subArray = [], itemSum = 0;
values.forEach(function(value) {
var singleItems = value.split(''),
charSum = 0;
singleItems.forEach(function(char) {
charSum += parseInt(char);
});
itemSum += charSum;
subArray.push(charSum);
console.log('Sum for chars of ' + value + ' = ' + charSum);
});
sumPerIndex.push(subArray);
totalSum += itemSum;
console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);

javascript: limit number of items

sorry but I'm new in javascrit.
I'm writing a simple rss reader, but I want to limit the number of feeds to 5 items, because the my target site can have 100 or more.
Here the code:
$("#mainPage").live("pageinit", function () {
$("h1", this).text(title);
$.get(RSS, {}, function (res, code) {
var xml = $(res);
var items = xml.find("item");
var items = $items.length && i < 5; i++); // here the problem!!
var entry = "";
$.each(items, function (i, v) {
entry = {
title:$(v).find("title").text(),
link:$(v).find("link").text(),
description:$.trim($(v).find("encoded").text()),
category:$.trim($(v).find("category").text()),
date:$(v).find("pubDate").text().substr(0,16),
autor:$(v).find("creator").text()
};
entries.push(entry);
});
var s = '';
$.each(entries, function(i, v) {
s += '<li>' + v.title + '<br><i>' + v.autor + ' - ' + v.date + '</i></li>';
});
$("#linksList").append(s);
$("#linksList").listview("refresh");
});
});
The problem is that when I try to limit the number of items adding
var items = $items.length && i < 5; i++);
the javascript stop to works. :-(
How to do it?
var items = $items.length && i < 5; i++); is invalid I think you want to
var items = items.slice(0, 4); is what you want.
https://api.jquery.com/slice/ (as pointed out to me, it's a jQuery object)
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
Because Javascript is 0-based (starts to count from 0) you want element 0 to 4, in order to get the first 5 elements.
You can use lt(n) function
var items = xml.find("item:lt(5)");

Finding average from input array with Javascript - not calculating correctly

I am trying to calculate the average of 3 values (each numbered from 1-10) that are selected by the user and then pass the results to an text input (for display as a graph).
It should be updating the new average every time one of the values is changed, but the averaging is not working correctly at all. I think that the loop is not resetting the values every time it runs- it's adding up the sum each time it runs, but not sure how to fix it.
Here is my code:
var sliders = $("#health1,#health2,#health3");
var elmt = [];
$(sliders).each(function () {
elmt.push($(this).attr('value'));
$("#health1,#health2,#health3").change(function () {
var sum = 0;
averageRisk();
});
});
function averageRisk() {
var sum = 0;
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i], 10);
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
elmt.push($(sliders).attr('value'));
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
Here is an example:
http://jsfiddle.net/pixelmix/783cfmnv/
Not sure but seems like a lot of extra work going. Main issue was you were building array of initial values and not getting the values each time they changed. That first .each got all the slider values and added them to elmt and continued to push new values on to after every change instead of just getting the current values every time. Did you want to accumulate all values over time?
Fiddle: http://jsfiddle.net/AtheistP3ace/783cfmnv/6/
$("#health1,#health2,#health3").on('change', function () {
averageRisk();
});
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
And as pointed out if you want to ignore updating things when the sum is NaN you can do this:
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
if (isNaN(sum)) {
return false;
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
The problem is that you fill the elmt array at page loading.
When user changes the values, you do not refresh the elmt array. So the array used to compute the average is always the same, empty.
You have to recover the input values each time they are modified.
function averageRisk() {
var sum = 0;
// Re make the loop for getting all inputs values
$(sliders).each(function() {
var value = parseInt($(this).val(), 10);
sum += value;
});
var avg = sum/$(sliders).length;
$('#healthLevel').val(avg);
}
Working example : http://jsfiddle.net/783cfmnv/7/
PS : You can use the css class healthInput to select your inputs. If you add later other fields, you will not have to add the new input id to your jQuery selector.
I did this work, check it .
http://jsfiddle.net/783cfmnv/10/
$("#health1,#health2,#health3").change(function() {
var val1 = +slider1.val();
var val2 = +slider2.val();
var val3 = +slider3.val();
var avg = (val1 + val2 + val3) /3;
$("#healthLevel").val(avg);
});

javascript sort placing middle item at top

I have the following sort function:
var timeArray = new Array('11:41', '11.39', '11:41', '11:41', '11:40', '11:70', '11:39', '11:38', '11:38', '11:37', '11:37');
timeArray.sort(function(c, d) {
var digit1 = parseInt(c.replace(/\D/g,''));
var digit2 = parseInt(d.replace(/\D/g,''));
return digit1 > digit2;});
var testContent = '';
for (var i = 0; i < timeArray.length; i++) {
testContent += timeArray[i] + '<br />';
}
$('#test').html(testContent);
Where I would expect to see the following result:
11:37
11:37
11:38
11:38
11.39
11:39
11:40
11:41
11:41
11:41
11:70
However, the 11.70 number always appears at the top of the results. If I change the 11:70 value in the array, no matter what value I use that is the one that will always appear at the start of the results.
Does anyone know how I can sort this properly and why the 11:70 always appears at the top of the list?
Example Fiddle
Change the sort function to
timeArray.sort(function(c, d) {
var digit1 = parseInt(c.replace(/\D/g,''));
var digit2 = parseInt(d.replace(/\D/g,''));
return digit1 - digit2;
});
FIDDLE
It's expecting a number to be returned, not a boolean.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Categories