emporio emporio - 22 days ago 4x
Javascript Question

Sort function behaves differently when put in a for loop

I've got two kinds of sort functions that are meant to sort an array of numbers and return the sum of the first two indexes however when these functions are run in a for loop, the second function doesn't work as it should.

Here is the first one:

function solution(numbers) {
numbers.sort(function (a, b) {
return a - b;
return numbers[0] + numbers[1];

Here is the second one:

function sumTwoSmallestNumbers(numbers) {
var findSmallest = function(startsAt){
var first = startsAt;
for (var i =0; i<=numbers.length-1; i++){
if(first >= numbers[i]){
first = numbers[i];
return first;
var smallest = findSmallest(numbers[0]);
var index = numbers.indexOf(smallest);
var secondSmallest = findSmallest(numbers[0]);
return smallest+secondSmallest

This is the for loop:

for (let i = 0; i < 100; i++) {
var randArr = [Test.randomNumber()+1000,Test.randomNumber(),Test.randomNumber(),Test.randomNumber(),Test.randomNumber()];
var staticArr = [1000, 50,12000, 275, 21000, 1];
console.log("Result of user function is: " + sumTwoSmallestNumbers(staticArr) + ". Result of own function is: " + solution(staticArr));
Test.assertEquals(sumTwoSmallestNumbers(randArr), solution(randArr));

See the console in the fiddle: https://jsfiddle.net/emporio/p4r7go57/1/


This modifies the input array, removing the smallest number. Every time you call sumToSmallestNumbers an item is removed, which changes the result the next time it's called.