0

I am trying to format my array to a formatted string, how can I do that? The instructions I was given are

Task 6 - find all odd numbers in a list.

Allow any number of Number arguments to be passed to the function. If a value is passed to the function that is not a Number, ignore it and continue processing the rest. If the list is empty (nothing passed to the function, or all need to be ignored, return null).

Return a formatted string with all odd numbers in a list, for example:

"1, 3, 5"

<script>
var odd = [];

const oddNumbers = (...numbers) => {
  var oddNum
  var formatString;
  var i;

  if (numbers.length > 0) {
    for (i = 0; i < numbers.length; i++) {
      if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
        odd.push(numbers[i]);
        console.log(odd);
      }
    }
  } else {
    return null;
  }
  return odd;
};

oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);

alert(odd);
</script>
4
  • numbers.filter(n => n % 2 !== 0).join(", ") Commented Sep 27, 2019 at 20:39
  • @epascarello That'll include non-numbers as well, and doesn't check for length 0 Commented Sep 27, 2019 at 20:40
  • I'd use const odds = []; for (let i = 0; i < numbers.length; i++) { const num = numbers[i]; if (typeof num === 'number' && num % 2 === 1) { odds.push(num); } } if (odds.length === 0) { return null; } return odds.join(', '); Commented Sep 27, 2019 at 20:40
  • not that hard to add non number check !isNaN(n) and is not really a full answer, hence a comment ;) Commented Sep 27, 2019 at 20:42

2 Answers 2

0

Just join your array into string:

else{
     return null;
}
return odd.join(', ');
Sign up to request clarification or add additional context in comments.

Comments

0

const oddNumbers = (...numbers) => {
  var odd = [];
  var oddNum
  var formatString;
  var i;

  if (Array.isArray(numbers)) {
    for (i in numbers) {
      if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
        odd.push(numbers[i]);
      }
    }
  } else {
    return [];
  }
  return odd;
};

var result = oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);

console.log(result.join(', '))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.