DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#28 - Sum of two lowest positive integers - CodeWars Kata (7 kyu)

Instructions

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

Example

Input --> [19, 5, 42, 2, 77]
Output --> 7

Input --> [10, 343445353, 3453445, 3453545353453]
Output --> 3453455.


My solution:

function sumTwoSmallestNumbers(numbers) {  
  let first = Math.min(...numbers)
  numbers.splice(numbers.indexOf(first), 1)
  let second = Math.min(...numbers)
  return first + second
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I used Math.min() with the array values so I could get the first smallest number.

let first = Math.min(...numbers)

After that I spliced the first number, so when I used Math.min() again I will get the second element

numbers.splice(numbers.indexOf(first), 1)
let second = Math.min(...numbers)

At the end I just returned the sum of the first and second number

return first + second


What do you think about this solution? πŸ‘‡πŸ€”

My Github
My twitter
Solve this Kata

Discussion (0)