javascript calling nested functions

Andrew

I'm new to coding and trying to figure out nested javascript functions. I've searched other questions but still can't figure it out. I'd like a function that takes a string of numbers seperated by spaces, converts the string to an array, and then outputs the result of a mathematical function on the array.

I've written something using the following outline and it works, but seems messy and don't know that I am really doing it the best way. I don't really understand how to call a function from another function.

    function doMathOnThisString(string) {
        var ar = convertStringToArray(string);
        return doMathOnArray(ar);

        function convertStringToArray(string) {
            //code that converts the original input string to an array
            return (ar)
        };

        function doMathOnArray(a) {
            //code that does math on an array
        }; 
}
codejockie

You're doing just fine with what you have, just take it a step further and you'd be fine. Kindly see my solution below:

function doMathOnThisString(string) {
  // Converts a string of numbers separated by spaces to an array
  function convertStringToArray(input) {
    return input.split(' '); // split input on spaces
  };

  // Sums up the value in the array of number string
  function doMathOnArray(numbersString) {
    return numbersString
      .map((number) => Number(number)) // Convert each (string) number to a proper number
      .reduce((acc, curr) => acc + curr); // Add each number
  };
  
  
  var stringNumberArray = convertStringToArray(string);
  return doMathOnArray(stringNumberArray);
}

const result = doMathOnThisString('1 2 3 4 5 6 7 8');
console.log(result);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related