Javascript Count numbers in a string - javascript

I need to count numbers in a string. The numbers are separated by spaces.
(1 2 3 4 10) I was trying to do this by charAt by that doesnt work if the number is not a single digit. I am relative new to JS and need some examples. I started with this but ran into a double digit #:
string1 = (1 1 1 4 10)
var total = parseFloat(0);
for(var j=0; j<string1.length; j++) {
total += parseFloat(string1.charAt(j));
}
Any help would be appreciated

I don't know why you need to do this way, but if this string comes from another font, you can deal with it, something like this:
var string1 = "(1 1 1 4 10)";
var aux = string1.replace("(","").replace(")","");
aux = aux.split(" ");
var total = parseFloat(0);
for(var j=0; j<aux.length; j++) {
total += parseFloat(aux[j]);
}
console.log(total);
https://jsfiddle.net/bggLkvxd/1/

Create an array:
var arr=[1,2,3]
and then do:
var count=0;
arr.forEach(function(number){
count+=number;
}
Or use a string:
var str="1 2 3";
var arr=str.split(" ");
var count=0;
arr.forEach(function(number){
count+=parseInt(number);
}
Count now contains the sum of all chars

// use method split to convert string to array and then add array items:
var string1 = "1 1 1 4 10", total = 0;
string1.split(" ").forEach(function(item) {
total += +item;
});

Here's a simpler way. First, fix string1 so it's actually a string (by adding " "s), also properly declare it with "var string". Then you could do something like this.
var string1 = ("1 1 1 4 10")
function addString(input) {
var sum = 0; //get your empty variable ready
var array1 = input.split(" "); //split your string into an array
for(var i=0; i<array1.length; i++) {
array1[i] = parseInt(array1[i]); // each new array element is integer
sum += array1[i]; // += is operator for solve/refactor
}
return sum;
}
addString(string1);

Related

How to get numbers 1-20 into an array, then separate even and odd numbers and print them on the web browser

Im new to Javascript and i cant figure out how to make this work. I have to use an array. I can only get it to show one of the numbers in the browser.
it prints:
Even Number = 20
I need it to print:
Odd Number = 1
Even Number = 2
Odd Number = 3
Even Number = 4
Odd Number = 5
Even Number = 6
Odd Number = 7
Even Number = 8
Odd Number = 9
Even Number = 10
Odd Number = 11
Even Number = 12
Odd Number = 13
Even Number = 14
Odd Number = 15
Even Number = 16
Odd Number = 17
Even Number = 18
Odd Number = 19
Even Number = 20
Here is what I have. Any help would be appreciated.
<script>
var numbers = [];
for (var i=1; i<=20; i++){
numbers.push(i);
if (i % 2 === 0){
document.getElementById("demo").innerHTML ="Even Number = "+i;
}
else {
document.getElementById("demo").innerHTML ="Odd Number = "+i;
}
}
</script>
That is because when you are doing document.getElementById("demo").innerHTML it is overwriting the previous content. Instead during each iteration create a div element and then append that as child of div#demo
var numbers = [];
for (var i = 1; i <= 20; i++) {
numbers.push(i);
let createElem = document.createElement('div');
let creatTxtNode;
if (i % 2 === 0) {
createTxtNode = document.createTextNode("Even Number = " + i);
} else {
createTxtNode = document.createTextNode("Odd Number = " + i);
}
createElem.appendChild(createTxtNode)
document.getElementById("demo").appendChild(createElem);
}
<div id='demo'></div>
Since you are assigning (=) the new value to the element, in each iteration the previous values are removed. You can either use += to concatenate the new value with the previous value OR try with insertAdjacentHTML():
var numbers = [];
var targetEl = document.getElementById("demo")
for (var i=1; i<=20; i++){
numbers.push(i);
if (i % 2 === 0){
targetEl.insertAdjacentHTML('beforeend', "Even Number = "+i + "<br>");
}
else {
targetEl.insertAdjacentHTML('beforeend', "Odd Number = "+i+ "<br>");
}
}
<div id="demo"><div>
You're on the right path with your solution. Just replace innerHTML = ... with innerHTML += ....
That will do the trick for you since with each iteration innerHTML operation is replacing your existing content, you actually need to append it.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
var copyNumbers = [];
var targetEl = document.getElementById("getNumbers")
numbers.forEach(function(i) {
copyNumbers.push(i);
switch (i % 2) {
case 0:
getNumbers.innerHTML += ("Even Number = <b><i>" + i + "</i></b><br />");
break;
default:
getNumbers.innerHTML += ("Odd Number = <b><i>" + i + "</i></b><br />");
}
});
<div id='getNumbers'></div>
Note:- you need to replace innerHTML = ... with innerHTML += .... each iteration instead of replacing your existing content, you need to append it.
<html>
<body>
<div id="demo"></div>
</body>
<script>
function evenOdd() {
//Create an array of even odd numbers result
evenOddArray = [...Array(20).keys()].map(x => {
if((x+1)%2==0){
return "Even Number = " + (x+1)
}
return "Odd Number = " + (x+1)
})
//loop through each result
evenOddArray.forEach(x => {
var t = document.createTextNode(x);// Create a text node
var br = document.createElement("br") // Create a new line node
document.getElementById("demo").appendChild(t) //append to demo
document.getElementById("demo").appendChild(br)
})
}
evenOdd()
</script>
</html>
https://jsfiddle.net/zpcu5mb8/
There are two key things.
First, as the others have noted, your use of innerHTML simply replaces the content each time which is why you're only getting the last output from the loop.
Second: "I have to use an array."
While you're pushing numbers to your array in your example ultimately it's pointless - you add numbers to it but don't use the array in any way. If it's a requirement for your work, you might get marked down for that.
So here's an example that fixes both issues:
1) It creates an array of numbers
2) It loops over that array of numbers and produces the output
// First we create out numbers array...
const numbers = [];
// ...and fill it with numbers
for (let i = 1; i <= 20; i++) {
numbers.push(i);
}
// We create an output array to store our strings
// You could concatenate the strings in the loop with `+=`
// but building an array and joining it up later is a little cleaner
const output = [];
// Now: loop over the numbers array
for (let i = 0; i < numbers.length; i++) {
// Grab the number. We want to check whether that
// is even/odd instead of the index
const number = numbers[i];
// Our condition: we push a different string to the array
// depending on whether its even/odd. I've used template literals
// as they're cleaner solution to using string concatenation
if (number % 2 === 0) {
output.push(`Even number = ${number}`);
} else {
output.push(`Odd number = ${number}`);
}
}
// Finally we grab our element
const demo = document.querySelector('#demo');
// And we add the joined up array to it
demo.insertAdjacentHTML('beforeend', output.join('<br/>'));
<div id="demo"></div>
Further reading
insertAdjacentHTML
Template literals

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

Better way to slice up a string?

I'm trying to take a string with blank spaces and display each word line-by-line in console output.
My javascript code takes a string and creates an array of indexes where spaces are identified using an indexOf() operation. This is then passed through a slice loop which subtracts the different indexes to get a length of the string to slice and the space index to locate it in the existing string. The output is the final console.log and it appears to do what I need it to even when passing in random strings.
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
console.log("string length = ", fourStr.length);
var i = 0;
var n = 0;
var sentence = [i];
for (n = 0; n < fourStr.length; n++) {
var pos = fourStr.indexOf(sp, n) //find the index of the space
if (n == pos) {
sentence[i] = pos; //place the index in an array
i++;
} else(i);
}
var arraysent = fourStr.split(sp); //test split function for string
console.log("Array Sentence:\n", arraysent)
console.log("space index length:\n", sentence.length) //check array length
console.log("space index array:\n", sentence) //display array with "space" indexes
console.log("sliced string:\n", fourStr.slice(sentence[0] - 1, sentence[0])); //display first index
var j = 0;
for (j = 0; j < sentence.length; j++) {
var slicesent = fourStr.slice(sentence[j], sentence[j + 1]); //automate remaining index display
console.log(slicesent);
}
I was hoping to find an easier/simpler way to do this same task since passing the string to the array is not efficient and re-creates the string a bunch of times. Could someone please explain a better alternative that will show the individual words of a string line-by-line in the console?
Thank you
This is literally done by String.split()
function logWordsBySpaces(str){
let arr = str.split(" ");
arr.forEach(function(a){ console.log(a); })
}
logWordsBySpaces("Karma karma karma karma karma chameleon!")
You should use .split
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
const result = [myStr, twoStr, stringadd, threeStr, fourStr].map(string => string.split(sp));
console.log(result);

How to get numbers from string in Javascript?

I have a strings that can look like this:
left 10 top 50
How can i extract the numbers, while the numbers can range from 0 to 100 and words can be left/right top/bottom? Thanks
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading #AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Split and extract the 2nd and 4th tokens:
var arr = "left 10 top 50".split(" ");
var a = +arr[1];
var b = +arr[3];
var str = 'left 10 top 50';
var splitted = str.split(' ');
var arr = [];
for(var i = 0 ; i < splitted.length ; i++)
{
var num = Number(splitted[i]);
if(!isNaN(num) && num >= 0 && num <= 100){
arr.push(num);
}
}
console.log(arr);
JSFIDDLE
If you want it dynamically by different keywords try something like this:
var testString = "left 10 top 50";
var result = getNumber("top", testString);
function getNumber(keyword, testString) {
var tmpString = testString;
var tmpKeyword = keyword;
tmpString = tmpString.split(tmpKeyword + " ");
tmpString = tmpString[1].split(' ')[0];
return tmpString;
}
var myArray = "left 10 top 50".split(" ");
var numbers;
for ( var index = 0; index < myArray.length; index++ ) {
if ( !isNaN(myArray[index]))
numbers= myArray[index]
}
find working example on the link below
http://jsfiddle.net/shouvik1990/cnrbv485/

Order elements from string

I've got a string!
7 serpents
4 bikes
2 mangoes
It's made up of number + [space] + thing-string. I need to be able to order the whole string with reference to the number. So it should come out:
2 mangoes
4 bikes
7 serpents
It's a simple bubble sort for the number and then cross-referencing the index to get the final order. The JavaScript code below works, but I can't help but think it could be made more efficient. Am I missing a trick here??
And remember: I'm an artist, so I code in crayon!
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
var splitArr = eventsStr.split("\n")
var numArray = new Array();
var events = new Array();
for (var i = 0; i < splitArr.length; i++)
{
var temp = splitArr[i] ;
var part1 = temp.substring(0, temp.indexOf(" "))
var part2 = temp.substring(temp.indexOf(" ")+1, temp.length)
numArray[i] = part1;
events[i] = part2;
}
var sorted = superCopy(numArray);
var sorted = sorted.sort(sortArrayNumerically);
alert(getOrder(sorted, numArray, events))
function getOrder(orderedarr, arr1, arr2)
{
var str = "";
for (var i = 0; i < arr1.length; i++)
{
for (var j = 0; j < orderedarr.length; j++)
{
if (arr1[i] == orderedarr[j])
{
// found the thing !what is the event?
str += arr1[i] + " " + arr2[i] + "\n";
}
}
}
return str
}
function sortArrayNumerically(a,b)
{
return a - b;
}
function superCopy(arr)
{
tempArr = new Array();
for (var i = 0; i < arr.length; i++)
{
tempArr[i] = arr[i]
}
return tempArr
}
You could use JavaScript's sort() function:
eventsStr.split('\n').sort().join('\n');
eventsStr.split('\n') - first split the string on the newline character to create an array
.sort() - then use the sort() function to sort the array
.join('\n') - then put the string back together, joining the array elements with a newline between them
Reference:
String.prototype.split()
Array.prototype.sort()
Array.prototype.join()
This is an alphabetic sort though, so if your string contained, say, 12 mangoes, the result would not be sorted numerically. To sort numerically, you could do something like this:
eventsStr.split('\n').sort(function(a, b) {
return parseInt(a.split(' ')[0], 10) > parseInt(b.split(' ')[0], 10);
}).join('\n');
In this situation, the sort() function is called with a callback parameter, taking 2 values: the first string to be compared and the second string to be compared. This callback function then splits the string, extracts the number and compares it with the number in the other string.
Use
splitArr.sort() // as per your code
DEMO
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
arr = eventsStr.split('\n')
# ["7 serpents", "4 bikes", "2 mangoes"]
arr
# ["7 serpents", "4 bikes", "2 mangoes"]
arr.sort()
# ["2 mangoes", "4 bikes", "7 serpents"]

Categories