Home > other >  How can I add all numbers from a string then divide 'em by four
How can I add all numbers from a string then divide 'em by four

Time:10-15

Ok so I need to create a prompt where it'll be added a few numbers separated by commas like this:

prompt('Insert here yours numbers separated by comma')

then i have to add an alert showing the result of the sum of each number divided by 4.

Like.... ok how am I supossed to strip each number from (1, 10, 33, 102, 00, etc) then add 'em altogether?

CodePudding user response:

You can split a string by a token e.g in your example by a comma (,)

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

const string = "1, 2, 3, 4, 5"
const arrayOfNumbers = string.split(", ") // gives you [1,2,3,4,5]

You might need to validate the array once it's splitted but that's not part of the question so I'll let you figure it out.

Next, you can operate on the array on a preferred method e.g foreach, for...of, reduce.

let total = 0

arrayOfNumbers.forEach((number) => {
  total  = parseInt(number)
})

for (const number of arrayOfNumbers) {
  total  = parseInt(number)
}

const total = arrayOfNumbers.reduce((prevValue, currentValue) => {
  return prevValue   parseInt(currentValue)
}, 0)

parseInt is necessary to convert the type into number instead of string.

If it was a string e.g "1" "1", they will be concatenated and will end up like "11".

Docs:

forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

for...of: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

CodePudding user response:

Is this what you are looking for?

var input = prompt('Insert here yours numbers separated by comma'); // input
var total = 0;
input.split(',').forEach((item)=> {total  = parseInt(item)}) // iterate on number 
alert(total); // aleart the result

the result of the sum of each number divided by 4 this part of the question is confusing are you asking for the sum of numbers divisible by 4 or dividing each number by 4 and then adding them?

if you need divisible by 4 just update forEach function

input.split(',').forEach((item)=> {if(parseInt(item) % 4 == 0)total  = parseInt(item)})
  • Related