Sum of two smallest numbers in an array, help me understand

Hey everyone, this is from code wars
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 .
I created this function

function sumTwoSmallestNumbers(numbers) {  
 a = Math.min.apply(Math, numbers); 
 numbers.splice(a);
 b = Math.min.apply(Math, numbers);
 return (a + b) 
}

So this code works sometimes. It passes some of the test but not all. If it didn’t work at all I would understand, but the fact that it works sometimes puzzles me.
What’s wrong with my function?

2 Likes

Array.splice works by indexes, but when you are trying to use it, you are passing the value, and not the position inside the array.

For example if your input is [19, 5, 42, 2, 77];
a is 2,
this means that your splice function is splice(2)
which means your array is now [ 42, 2, 77 ].

Here you can find the full documentation of Array.splice

3 Likes

Thank you. I think I get it now

@Imstupidpleasehelp so, would we just toss a 0 in there between Math and number so that we just get the number at the index of ?