If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.
If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.
Kata #17
DESCRIPTION:
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.
For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
[10, 343445353, 3453445, 3453545353453] should return 3453455.
Starting code:
function sumTwoSmallestNumbers(numbers) {
//Code here
}
My attempt that worked:
function sumTwoSmallestNumbers(numbers) {
let sortedNumbers = numbers.sort((a,b)=>a-b)
return Number(sortedNumbers[0]) + Number(sortedNumbers[1])
}
Then shortened it to this:
function sumTwoSmallestNumbers(numbers) {
let sortedNumbers = numbers.sort((a,b)=>a-b)
return sortedNumbers[0] + sortedNumbers[1]
}
I was thinking of ways to shorten it further to a one-liner but my mind was drawing a blank on how to proceed after the .sort() method so I just went and submitted it to see the best practices.
Rank #1:
function sumTwoSmallestNumbers(numbers){
numbers = numbers.sort(function(a, b){return a - b; });
return numbers[0] + numbers[1];
};

+ *feelsgoodman.jpg*
Ranks #2 and #3 are more of the same, with just a slight difference in variable declaration.
Rank #4 with a for loop:
function sumTwoSmallestNumbers(numbers) {
var min = Number.MAX_SAFE_INTEGER;
var secondMin = Number.MAX_SAFE_INTEGER;
var n;
for (i = 0; i < numbers.length; i++) {
n = numbers[i];
if(n < min) {
secondMin = min;
min = n;
} else if( n < secondMin ) {
secondMin = n;
}
}
return min + secondMin;
}
Rank #5 with the one-liner, thanks to users Unihedron, praveensiddartha, oussemaa12, mounira zouabi for the submission:
const sumTwoSmallestNumbers = numbers => numbers.sort((x, y) => x - y).slice(0, 2).reduce((x, y) => x + y);
Rank #6 is also a one-liner by user andorey but using var instead of const:
var sumTwoSmallestNumbers = (numbers) => numbers.sort((a,b)=> a-b).slice(0, 2).reduce((a,b)=> a+b)
That's it for Kata #17, stay tuned for more katas to be solved!
Link to Kata #1: Square(n) Sum
Link to Kata #2: Convert a Number to a String
Link to Kata #3: DNA to RNA Conversion
Link to Kata #4: Remove First and Last Character
Link to Kata #5: MakeUpperCase
Link to Kata #6: Total amount of points
Link to Kata #7: A Needle in the Haystack
Link to Kata #8: Sum of positive
Link to Kata #9: Basic Mathematical Operations
Link to Kata #10: Beginner - Reduce but Grow
Link to Kata #11: Square Every Digit
Link to Kata #12: Friend or Foe?
Link to Kata #13: Grasshopper - Summation
Link to Kata #14: Get the Middle Character