JavaScript Code Exercises 1

JavaScript Code Exercises 1

Write a function that takes an array of numbers and returns the sum of all the positive numbers in the array.
Write a function that takes an array of strings and returns the shortest string in the array.
Write a function that takes a string and returns a new string with all the vowels removed.
Write a function that takes an array of numbers and returns a new array with all the even numbers removed.

Write a function that takes an array of numbers and returns the sum of all the positive numbers in the array.

function sumOfPositiveNumbers(numbers) {

  let sum = 0;

  for (let i = 0; i < numbers.length; i++) {

    if (numbers[i] > 0) {

      sum += numbers[i];

    }

  }

  return sum;

}

Explanation: This function iterates over the array using a for loop and adds up all the positive numbers it encounters. The sum is stored in the sum variable and is returned at the end.

Write a function that takes an array of strings and returns the shortest string in the array.

function findShortestString(strings) {

  let shortest = strings[0];

  for (let i = 1; i < strings.length; i++) {

    if (strings[i].length < shortest.length) {

      shortest = strings[i];

    }

  }

  return shortest;

}

Explanation: This function uses a for loop to iterate over the array and keep track of the shortest string it has encountered so far. The shortest variable is initialized to the first string in the array, and is updated whenever a shorter string is found.

Write a function that takes a string and returns a new string with all the vowels removed.

function removeVowels(str) {

  return str.replace(/[aeiou]/gi, ”);

}

Explanation: This function uses the replace method on the string to remove all occurrences of the vowels (both upper and lowercase) using a regular expression.

Write a function that takes an array of numbers and returns a new array with all the even numbers removed.

function removeEvenNumbers(numbers) {

  return numbers.filter(num => num % 2 !== 0);

}

Explanation: This function uses the filter method on the array to create a new array with only the odd numbers