How to split String, convert to Numbers and Sum - javascript

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);

Related

Looping through an array that has binary numbers and writing true if the number is 1 or false if the number is 0

I am trying to make a webpage that makes an encrypted letter by first parsing a single character in ascii then parsing the ascii into binary then putting the binary into an array. After putting it into an array I have to loop through the array and write true for "1" or false for "0". Then I have to output to the page. an example of what the output would look like if you put in the letter "a" would be "false,true,true,false,false,false,false,true"
Update: I have added the "loop" in order to make sense of my problem
$(document).ready(function()
{
var output = document.getElementById("output");
var strQuestion = "Enter ONE character, matey!";
var strStandard = "J";
var chrCharacter = "";
var chrLength = 0;
var array = [];
var arrayLength = 0;
while (chrLength != 1)
{
chrCharacter = prompt(strQuestion, strStandard);
chrLength = chrCharacter.length;
}
intAscii = parseAscii(chrCharacter);
strBin = parseBin(intAscii);
array = strBin.split("");
for (i = 0; i < arrayLength; i++ )
{
if (array[i] = 0)
{
array[i] = false;
}
else if (array[i] = 1)
{
array[i] = true;
}
}
output.innerHTML = array;
}); //end document.ready
/*****
Purpose: Converts a character into ascii
Parameters: single character / letter
Return: integer representing an ascii value
*****/
function parseAscii(chrCharacter)
{
intAscii = chrCharacter.charCodeAt(0);
return intAscii;
}
/*****
Purpose: Takes the ascii code and turns it into binary
Parameters: single integer representing an ascii value
Return: binary, base 2 representation of the number passed to this function
*****/
function parseBin(intAscii)
{
strBin = parseInt(intAscii, 10).toString(2);
if(strBin.length < 8)
{
var intPlaceHolders = 8 - strBin.length;
for(var i = 0; i < intPlaceHolders; i++)
{
strBin = "0" + strBin;
}
}
return strBin;
}
I would convert the array with binaries to an array with boolean values wich you can joint together to a string that can be shown on the webpage.
array = [1,1,0,0,1]
// This will map over the items and perform an type conversion
var booleanArray = array.map(Boolean)
// Join all the items together as a string
Var booleanString = booleanArray.join(", ")
output.innerHTML = booleanString
`
I didn't test it, but it should work if I didn't make any typo's.
Btw, I dont think that this is what they ment with looping. But it's definitely a way to get the job done.
If I understand your question correctly, you can convert your array of ones and zeros (binary) to values of ture and false using the map function and using innerHTML to add the output to the DOM:
See example below:
// Populate myBinaryArray using your ascii method to get the follow:
let myBinaryArray = [1, 0, 0, 1, 1, 0, 1];
document.body.innerHTML += myBinaryArray.map(bit => !(!bit));

I want to take the first number from an array and depending on its index put equal amount of 0 next to it

edit: without giving me too much of the answer to how i can do it in a for loop. Could you give me the logic/pseudocode on how to achieve this? the one part i am stuck at is, ok i know that i have to take the first index number and add array.length-1 zeros to it (2 zeros), but i am confused as to when it arrives at the last index, do i put in a if statement in the for loop?
In the below example 459 would be put in an array [4,5,9]
Now I want to take 4 add two zeros to the end because it has two numbers after it in the array
Then I want to take 5 and add one zero to it because there is one number after it in the array.
then 9 would have no zeros added to it because there are no numbers after it.
So final output would be 400,50,9
how can i best achieve this?
var num=459;
var nexint=num.toString().split("");
var finalint=nexint.map(Number);
var nextarr=[];
You need to use string's repeat method.
var num=459;
var a = (""+num).split('').map((c,i,a)=>c+"0".repeat(a.length-i-1))
console.log(a);
Here's another possible solution using a loop.
var num = 459;
var a = ("" + num).split('');
var ar = [];
for (var i = 0; i < a.length; i++) {
var str = a[i];
str += "0".repeat(a.length-i-1);
ar.push(str);
}
console.log(ar);
You could use Array#reduce and Array#map for the values multiplied by 10 and return a new array.
var num = 459,
result = [...num.toString()].reduce((r, a) => r.map(v => 10 * v).concat(+a), []);
console.log(result);
OP asked for a solution using loops in a comment above. Here's one approach with loops:
var num = 459
var numArray = num.toString().split('');
var position = numArray.length - 1;
var finalArray = [];
var i;
var j;
for(i = 0; i < numArray.length; i++) {
finalArray.push(numArray[i]);
for(j = 0; j < position; j++) {
finalArray.push(0);
}
position--;
}
console.log(finalArray);
The general flow
Loop over the original array, and on each pass:
Push the element to the final array
Then push X number of zeros to the final array. X is determined by
the element's position in the original array, so if the original
array has 3 elements, the first element should get 2 zeros after it.
This means X is the original array's length - 1 on the first pass.
Adjust the variable that's tracking the number of zeros to add before
making the next pass in the loop.
This is similar to #OccamsRazor's implementation, but with a slightly different API, and laid out for easier readability:
const toParts = n => String(n)
.split('')
.map((d, i, a) => d.padEnd(a.length - i, '0'))
.map(Number)
console.log(toParts(459))

JS string to array of number

So i have this string
first €999, second €111
Im trying to make an array that looks like this (numbers after every €)
999,111
Edit:
Yes i have tried to split it but wont work. i tried to look it up on google and found something with indexof but that only returned the number of the last €.
rowData[2].split('€').map(Number);
parseInt(rowData[2].replace(/[^0-9\.]/g, ''), 10);
split(rowData[2].indexOf("€") + 1);
The numbers are variable.
var input ="first €999, second €111";
var output=[];
var arr = input.split(",");
for(var i=0;i<arr.length;i++)
{
output.push(parseInt(arr[i]));
}
var output_string = output.stingify();
console.log(output); //Output Array
console.log(output_string); //Output String
If the numbers will always be of 3 digits in length, you can do this. If not, you need to specify a bit more.
var string = "€999, second €111";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].substring(temp[i].indexOf("€"),3));
}
//digitArray now contains [999,111];
Edit, based on your requirement of variable digit lengths
var string = "€999, second €111, third €32342";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].replace(/^\D+/g, '')); //Replace all non digits with empty.
}
//digitArray now contains [999,111,32342]

sum of uint8array javascript

I'm trying to sum and then average a stream of data, some code here.
var getAverage = function(dataArray){
var total,
sample = dataArray.length,
eArray = Array.prototype.slice.call(dataArray);
for (var i = 0; i< sample; i++) {
total+= eArray[i];
}
return total;
}
var output = function(){
//source data
var dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
var average = getAverage(dataArray);
$('#average').text(average);
window.requestAnimationFrame(output);
Every element in the array returns a number, but it still returns NaN. Help?
Set total = 0; currently it is defaulting to undefined. undefined + a number = NaN, and NaN + a number = NaN.
The declared variable total is undefined which means it will create NaN (Not-a-Number) when a number is added to it.
Also, Typed Array (ArrayBuffer/views) and Array are not the same, and converting a typed array to an ordinary Array is making iteration slower as typed arrays are actual byte-buffers while Arrays are (node) lists. That on top of the cost of conversion itself.
Just add them straight forward. Remember to divide the sum on length and of course to initialize total:
var getAverage = function(dataArray){
var total = 0, // initialize to 0
i = 0, length = dataArray.length;
while(i < length) total += dataArray[i++]; // add all
return length ? total / length : 0; // divide (when length !== 0)
}

Sum of a string of one-digit numbers in javascript?

I'm trying to write a script that adds the left side of a string and validates it against the right side.
For example:
var left = "12345"
var right = "34567"
I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7.
I just don't have a clue how to do it.
I think I need to use a for loop to iterate through the numbers such as
for (var i = 0, length = left.length; i < length; i++)
But I'm not sure how to add each number from there.
EDIT the var is actually being pulled in from a field. so var left = document.blah.blah
DEMO
var left = "12345"
var right = "12345"
function add(string) {
string = string.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
return sum; //return when done
}
alert(add(left) === add(right));​
Find the length of the string
then in a temp Variable store the value pow(10,length-1)
if you apply module function (left%temp) you will ge the Last significant digit
you can use this digit to add
repeat the process till the length of the string left is 0
6 Repeat all the steps above for the right as well and then compare the values
Note: convert the string to int using parseInt function
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
stringSum(a) == stringSum(b)

Categories