'Js How to got the sum of numbers from a string?
I'm new to coding and have been given this question;
Create a function that takes a string with a jumble of letters and numbers. It should add together all the numbers that appear in the string and return the total.
E.g. 'foo5bar6cat1' => 12
'foo99cat' => 18
Tip: For this one, it might be useful to know that the value NaN
in JavaScript behaves oddly. For example, if you do typeof NaN
it tells you it's a "number"
. Odd, eh?
The code that I have written is this;
function sumDigitsFromString(str) {
let nums = []
let sum = 0
for (let i = 0; i < str.length; i++) {
if (typeOf (arr[i]) === "number") {
nums.push(str[i])
}
}
for (let i = 0; i < nums.length; i++){
sum.push(nums[i] + sum)
}
return sum
}
The test that my code is being run against is this;
describe("sumDigitsFromString", () => {
it("picks out a digit from a string and returns", () => {
expect(sumDigitsFromString("foo5foo")).to.equal(5);
});
it("sums multiple digits from a string", () => {
expect(sumDigitsFromString("5foo5foo")).to.equal(10);
});
it("returns a seum of several digits in a string", () => {
expect(sumDigitsFromString("hello1world5this3is2a2string")).to.equal(13).;
});
});
Dose anyone have any suggestion of how to fix my code?
Solution 1:[1]
function numberAdd(str){
var strArr = str.split(""), strTemp=0;
for(i=0;i<strArr.length;i++){
if(!isNaN(strArr[i])){
strTemp+=parseInt(strArr[i]);
}
}
return strTemp;
}
var str = 'foo5bar6cat1';
console.log(numberAdd(str));
Solution 2:[2]
Your method won't work because of so many reasons, Try to change your method as following and it should do the trick,
function sumDigitsFromString(str) {
var sum = 0;
var numbers = str.match(/\d+/g).map(Number);
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i]
}
return sum;
}
Solution 3:[3]
You're almost on the right track.
if (typeOf (arr[i]) === "number") {
I think you meant to use str[i]
instead of arr[i]
. arr
was not defined earlier.
if (typeof(str[i]) === "number") {
This will always be false. Every str[i]
is a string. Correct is using:
if (!isNaN(Number(str[i]))) {
where if str[i]
is not a number, Number(str[i])
will return NaN
.
nums.push(str[i])
You need to push numbers not strings. Use Number(str[i])
.
sum.push(nums[i] + sum)
sum
is of type Number. You can't push to a number. You need to add to that number. Use sum += nums[i]
instead.
So the complete, working code will be:
function sumDigitsFromString(str) {
let nums = [];
let sum = 0;
for (let i = 0; i < str.length; i++) {
if (!isNaN(Number(str[i]))) {
nums.push(Number(str[i]));
}
}
console.log(nums);
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}
// Test it
console.log(sumDigitsFromString("foo5bar6cat1"));
Solution 4:[4]
An alternative solution if you are solving for numbers as the combination of a series within a string (ie 'zz11yx33ab' -> 44) or ('020a010b030c11' -> 71).
let string = '020a010b030c11';
function sumNumbers(string) {
let pos = 1;
let numArray = [];
let numString = null;
for (let num of string) {
let isParsed = isNaN(parseInt(num));
if (!numString && !isParsed && pos === string.length) {
numArray.push(num);
} else if (!numString && !isParsed && pos !== string.length) {
numString = num;
} else if (numString && !isParsed && pos === string.length) {
numString += num;
numArray.push(numString);
} else if (numString && isParsed && pos === string.length) {
numArray.push(numString);
} else if (numString && !isParsed) {
numString += num;
} else if (numString && isParsed && pos !== string.length) {
numArray.push(numString);
numString = null;
} else if (!numString && isParsed && pos === string.length) {
numString += num;
numArray.push(numString);
}
pos++;
}
console.log('numAray:', numArray);
let result = null;
for (let num of numArray) {
let value = parseInt(num);
result += value;
}
return result;
}
let finalNum = sumNumbers(string);
console.log(finalNum);
Solution 5:[5]
typeOf
is supposed to betypeof
. You don't want this in your code though because it will give all the elements in the string array a string value.Use
parseInt()
to make all the elements in the array numbers and then weed out the ones who returnNaN
withisNaN()
function sumDigitsFromString(str) { let nums = [] let sum = 0 for (let i = 0; i < str.length; i++) { if (!isNaN(parseInt(str[i]))) { sum += parseInt(str[i]) } } return sum }
Solution 6:[6]
let sum =0;
for(char of string)
isNaN(parseInt(char)) ? sum=sum+0:sum=sum+parseInt(char);
this should serve the purpose....ES6 syntax used.
Solution 7:[7]
let test = 'naseef123hello66'
//declared an empty array
let nums = [];
//declared a sum variable
let sum = 0;
//check whether it is number or alphabet
for(i=0;i<test.length;i++){
if (!isNaN((test[i]))) {
nums.push(Number(test[i]));
}
}
//itrating arr and find sum with basic arithmetic operation
for (k=0;k<nums.length;k++){
sum = sum + nums[k]
}
console.log("sum : "+sum)
let test = 'naseef123hello66'
//declared an empty array
let nums = [];
//declared a sum variable
let sum = 0;
//check whether it is number or alphabet
for(i=0;i<test.length;i++){
if (!isNaN((test[i]))) {
nums.push(Number(test[i]));
}
}
//itrating arr and find sum with basic arithmetic operation
for (k=0;k<nums.length;k++){
sum = sum + nums[k]
}
console.log("sum : "+sum)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user9054560 |
Solution 2 | Sandeepa |
Solution 3 | Wais Kamal |
Solution 4 | |
Solution 5 | Derf Mongrel |
Solution 6 | Reactgular |
Solution 7 |