Oddball_Sum Challenge

Hi,

I am currently learning Javascript and need the Ruby answer to the
following answer translated into Javascript. Here is the challenge;

Write a function oddball_sum(numbers), which takes in an array of
integers and returns the sum of all the odd elements.

Ruby CORRECT answer below;

def oddball_sum(numbers)
result = 0
numbers.each { |n| result += n if n %2 != 0 }
return result
end
puts oddball_sum([1,4,1,2])

My WRONG Javascript answer;

function oddball_sum(numbers) {
var answer = 0;
for (var i = 0; i <= numbers.length; i++){
if (numbers[i] % 2 !== 0)
return answer += i;
}
}
oddball_sum ([1,2,3,4,5])

def oddball(array)
array.inject(0){|sum,x|sum+(x.to_i.odd? ? x : 0)}
end

Don’t return before the loop finishes.
Don’t take one index too much in the loop. Valid indices are from 0 to
length-1.
Do add the actual numbee, not the index to the result.
Javascript does not separatw floats and integers, so don’t expect the
result to be exactly 0 or 1.

function oddball_sum(numbers) {
var answer = 0;
for (var i = 0; i < numbers.length; i++){
if ( Math.abs(numbers[i] % 2 - 1) < 1E-2 )
answer += numbers[i];
}
return answer
}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs