JS string to array of number - javascript

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]

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

Return first value of array based on second value [duplicate]

This question already has answers here:
How to add same elements to javascript array n times
(4 answers)
Closed 4 years ago.
I've been trying to figure this problem out for a while but I'm at a blank. Here's what I have so far:
var repeatNumbers = function(data) {
var repeated = [];
for ( var x = 0; x < data.length; x++){
var unit = data[x][0]
var quant = data[x][1]
for(var i = quant; i > 0; i--){
repeated.push(unit);
repeated.join(',');
}
return repeated;
}
};
console.log(repeatNumbers([1, 10]));
Basically I'm trying to repeat the first number of the array based off of the second value. Any insight would be greatly appreciated thank you! :)
You don't need to loop over your array if you only have two numbers, where the first number (at index 0) is the number you want to repeat, and the second number is the number of times you want to repeat that number (index 1).
Once you have the number of times you wish to repeat the number, you can simply use a for loop to enter the number into your repeated array that number of times.
See working example below (read code comments for further explanation):
var repeatNumbers = function(data) {
var repeated = []
var toRepeat = data[0]; // get the first number in the array
var times = data[1]; // get the second number in the array
// loop the number of times you want to repeat the number:
for(var i = 0; i < times; i++) {
repeated.push(toRepeat); // push the number you wish to repeat into the repeated array
}
return repeated.join(); // return the joined array (as a string - separated by commas)
}
console.log(repeatNumbers([1, 10]));
If I understand your question correctly, you want the function repeatNumbers() to return an array with the first element in the passed array replicated by the second element in the passed array.
To achieve that, you could do the following:
var repeatNumbers = function(data) {
// Extract the "value" to be repeated, and the "repeated" value
// that will control the number of "value" items in result array
var value = data[0];
var repeated = data[1];
var result = []
// Loop over repeated range, and push value into the result array
for (var i = 0; i < repeated; i++) {
result.push(value);
}
// Result result array
return result;
};
console.log(repeatNumbers([1, 10]));
Or, if you don't need to support IE, a more consise approach would be:
var repeatNumbers = function(data) {
var value = data[0];
var repeated = data[1];
return (new Array(repeated).fill(value));
};
console.log(repeatNumbers([1, 10]));

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

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)

How to check first character in string and how to send that string into an array in Jquery?

friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});

Categories