How to Split String and get Number form it? - javascript

I have one string "I_am_125_developer_25" and want result 150 means 125+25 using javascript
var a = "I_am_125_developer_25";
I tried following solution
for(var i = 0; i<= a.length; i++)
{
if(typeof a[i] == Number)
{
var c = a[i]; console.log(c);
}
}
Here I need to add two numbers from string need to check whether it is number or not.

Try
"I_am_125_developer_25".match(/\d+/g).reduce( (a,b) => Number(a) + Number(b) )
Explanation
Match numbers, get the array ["125", "25"]
Reduce the array by adding the converted (to Number) array items (reference here)
Edit
If you also want to support the scenarios like "I_am_1x5_developer_25", then make it
"I_am_1x5_developer_25".split(/_/).filter( s => !isNaN(s) ).reduce( (a,b) => Number(a) + Number(b) );
Explanation
split by _
filter out non-numeric values
Reduce the array by adding the converted (to Number) array items

function getSumFromString(str) {
var total = 0;
str.split('_').forEach(function(e){
var num = parseInt(e);
if(num) {
total +=num;
}
});
return total;
}
getSumFromString('I_am_125_developer_25');

I got the solution
var total = 0;
for(var i=0; i<=arr.length; i++){
if(!isNaN(arr[i])) {
total+=Number(arr[i]);
}
}
console.log(total);

A simple solution would be to split the string and make it an array, loop through it, verify which are numbers using isNaN() method and sum up the numbers:
var a = "I_am_125_developer_25";
a = a.split('_');
var sum = 0;
for(var i = 0; i < a.length; i++){
if(!isNaN(a[i])){
sum += parseInt(a[i]);
}
}
console.log(sum);

Try this:
var string = "I_am_125_developer_25";
var regex = /(\d+)/g;
var numArray = string.match(regex);
var sum=0;
for (var i=0;i<numArray.length;i++){
sum+=parseInt(numArray[i]);
}
console.log(sum);

Related

Splitting Numbers and adding them all - JavaScript

I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4

Sum of Digits using tostring and number methods javascript

Can someone explain what I am doing wrong in this problem? I want to add the sum of the num variable using toString and Number methods. I first turn num into the string num = '12345'. Then I loop through string, turn it into a number and add it to the sum.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num.toString();
for(var i = 0; i < num.length; i++){
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
You're not assigning the result of num.toString() to anything.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num = num.toString();
for (var i = 0; i < num.length; i++) {
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
console.log(sumDigits(num));
I believe you can use this one :
var num = 12345;
function sumDigits(num) {
//empty variable
var str;
//check type of the incoming value
(typeof num == "string") ? str = num : str = num.toString();
//this is the same with above if you don't know how to use short handed if else
/*
if(typeof num == "string"){
str = num;
} else {
str = num.toString();
}
*/
//Array's split Method and a variable which u have create already
var arr = str.split(''), sumOfDigits = 0;
for(var i in arr){
//You should use parseInt() method.
sumOfDigits += parseInt(arr[i]);
}
//return the sum of the digits
return sumOfDigits;
};
console.log(sumDigits(num));
If you have future problems please first search a bit then write here :)
Updated:
You can use split, map and reduce to split the array, map it to integers, then use a reduce function to sum the integers.
You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = num
.toString()
.split('')
.map(function(n) { return parseInt(n);})
.reduce(function(acc, val) {
return acc + val;
},
0
);
return sumOfDigits;
}
var sum = sumDigits(num);
console.log(sum)

Return a piece of an array after finding the highest integer in java script?

So after working on finding the highest sum of any given amount of credit card numbers I realized I dug myself into a bit of a hole. (currently using 3 cards "123-123, 234-234 and 345-345" as test numbers.) After writing this out:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre);
var highest = sumpre[0];
for (var i=1; i<=sumpre.length; i++){
if (sumpre[i]>highest){
highest=sumpre[i];
}
}
console.log(highest)
Which works to find the highest sum, however; I need it to return the card number with the highest sum in its original form at the end and am not sure what method would be best to get back to that or if I should reformat it from the start.
As I mentioned in a comment, or as shown in Gerardo's answer, one way to do it with minimal changes to your current code is to use highest to keep the index of the array item with the highest value, instead of keeping the actual value itself - then you could retrieve the original card value via that index.
But for fun, here's another way to do it:
function sumDigitsInString(s) {
return Array.prototype.reduce.call(s, function(p, c) { return p + (+c || 0); }, 0);
}
function itemWithLargestSum(a) {
return a.reduce(function(p, c) {
var sum = sumDigitsInString(c);
return p[0] > sum ? p : [sum, c];
}, [0])[1];
}
// given an array of strings:
var input = ["123-123", "234-234", "345-345", "111-111"];
var largest = itemWithLargestSum(input);
console.log(largest);
Further reading:
.call() method
Array .reduce()
Unary plus operator
|| operator
?: (ternary) operator
You could also do something like this, just with Array methods.
var inputCards = ["989-000", "123-999", "456-456"];
var sum = 0,
sumNumbers = {},
maxVal = 0;
inputCards.map(function(num) {
var replaceText = new RegExp(/-/g);
var number = num.replace(replaceText, "").split("");
var prevVal = 0;
sumNumbers[num] = number.reduce((prevVal, currentVal) =>
parseInt(prevVal, 10) + parseInt(currentVal, 10));
});
console.log(Object.keys(sumNumbers).reduce((maxVal, currentVal) =>
sumNumbers[maxVal] > sumNumbers[currentVal] ? maxVal : currentVal));

Comparing sums of elements within an array to determine which is the highest

I am trying to create a single function in Javascript that will take each element of an array of numbers (specifically phone numbers in this case) and determine which element has the highest sum. I have reached a point where I am feeling pretty defeated, yet I think I am very close. Can anyone give some guidance? This is what I have so far:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
I set the variables I am going to use, then created a for loop to iterate over each element in the array.
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
I create a place holder string to remove any non integers in the element, then create a function that will sum all the digits of the element.
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
Then create an if statement that tests if the sum of the current element is higher or equal to the highest sum element.
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
Here is the entire code block as a whole:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
I get "undefined" as the result when I run the code if that helps. Thank you in advance for your assistance.
If I'm interpreting this question correctly (add each number of a phone number, then print the largest result), you can accomplish it like this:
//Define an array of phone numbers
var numbers = ['123-456-7777', '111-222-3333', '963-481-7945'];
//Map takes an array, does something with each element, then returns that result
var sums = numbers.map(function (m) {
//In this case, we return an object containing the original number, and a score
return {
number: m,
//The score is calculated by adding up each number. The match expression creates an array of all terms (g modifier) matching the expression. \d matches a single digit, so we end up with an array of each digit in the number.
//Reduce applies a function to each item in an array, and adds them up
score: m.match(/\d/g).reduce(function (p, c) {
//This looks like magic, but the + before p and c coerces them to numbers (they're strings right now, since match returns an array of strings)
//Both numbers are then added
return +p + +c;
})
}
}).sort(function (a, b) {
//Now that we have the scores of all numbers, we can sort the array to find the highest score
//To be honest, sort() is mostly trial and error for me to find which values to return 1 and -1 for
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
//All together, without comments:
sums = numbers.map(function (m) {
return {
number: m,
score: m.match(/\d/g).reduce(function (p, c) {
return +p + +c;
})
}
}).sort(function (a, b) {
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
console.log(sums);
document.write("Number with the highest score: " + sums[0].number);
document.write("<br>");
document.write("It's score is " + sums[0].score);
Which prints the number with the largest sum to the console. The sum of the numbers is also available in the object that is returned in the score property.
In your code, you are not initializing the sum variable here and you are prematurely returning the sum value in this function:
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
It should be this:
function sumDigits(str) {
var sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}
return sum;
}
We can't really see what else is wrong without seeing all the code together in one block so we can see how different parts call each other and interact.
Here's a more compact solution (assuming you're trying to sum the digits in each phone number):
var phoneNumbers = ["123-456-7890", "982-111-9999"];
var sums = phoneNumbers.map(function(p) {
return p.match(/\d/g).reduce(function(sum, num) {
return sum + parseInt(num, 10);
}, 0);
});
var maxSum = Math.max.apply(Math, sums);
// output results in the snippet window
document.write("sums = " + JSON.stringify(sums) + "<br>");
document.write("maxSum = " + maxSum + "<br>");
Here's how it works:
Run .map() on the phone numbers array with the goal of returning an array of sums.
Within the .map() search for all digits, then run .reduce() on that resulting array to accumulate the sum.
Then, to get the max value in the sums array, use Math.max() which can accept the entire array and do the max work for you.

Trying to square every digit of a number, but my algorithm is not working?

I'm trying to square every digit of a number;
for example:
123 should return 149
983 --> 81649 and so on
I messed it up somewhere in the following Javascript code and I'm looking for some guidance.
function splitNumber(num){
var arr = [];
while(num>0){
var c = num%10;
arr[arr.length]=c;
num=num/10;}
return arr;
}
function squareArrToNumber(arr){
var c = 0;
for(var i=arr.length-1;i>=0;i--){
arr[i]=arr[i]^2;
if(arr[i]^2>10)
c = c*100+arr[i];
else
c = c*10+arr[i];
}
return c;
}
function squareDigits(num){
squareArrToNumber(splitNumber(num));
}
Try out this code
function numToSqr(num){
var i, sqr=[],n;
num = num.toString();
for(i=0;i<num.length;i++){
n = Number(num[i]);
sqr.push(n*n);
}
return Number(sqr.join(""));
}
There are multiple things wrong with your code, starting with an overcomplication to split a string of numbers into its consituant characters just use .splt(""):
var str = "123";
var arr = str.split("");
for(var i = 0;i<arr.length;i++)
alert(arr[i]);
Next, the code num ^ 2 does not square a number. To do a square, simply multiply a number by itself (num * num)
This leaves us with a rather simple solution
function splitNumber(num){
return num.split("");
}
function joinArray(arr){
return arr.join("");
}
function squareArrToNumber(arr){
var newArr = [];
for(var i=0;i<arr.length;i++){
newArr.push(arr[i] * arr[i]);
}
return joinArray(newArr);
}
function squareDigits(num){
return squareArrToNumber(splitNumber(num));
}
alert(squareDigits("123"));
alert(squareDigits("983"));
Here is how I would do such a thing:
var num = 123;
var numArray = num.toString().split("");
var result = "";
for(var i = 0; i < numArray.length; i++){
result += parseInt(numArray[i]) * parseInt(numArray[i]);
}
function squareNum(number) {
var array = [];
// Split number into an array of numbers that make it up
array = String(number).split('');
for (let i = 0; i < array.length; i++) {
// Take each number in that array and square it (in place)
// Also can be done with forEach depending on what es version you're targetting
array[i] = Math.pow(array[i], 2);
}
// combine and return the elements of the array
return Number(array.join(''));
}
squareNum(123);
squareNum(983);
try this example
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.
if(arr[i]^2>10)
should be
if(arr[i]>10)
And, as #Luaan noted, it should be
arr[i] *= arr[i]

Categories