Exodus Reed
Exodus Reed

Reputation: 307

for loop inside a function being called in another function's for loop javascript

I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (i = 0; i < nums.length; i++) {
    smallest_index = find_smallest(nums);
    arr.push("5");
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

console.log(sortArray(nums));

any help or thoughts as to what i may be not be realizing or doing ?

Upvotes: 0

Views: 637

Answers (1)

kdiv
kdiv

Reputation: 11

The problem is within your for loops. More specifically, you need to declare the variable i before using it. If you alter your code like the below snippet, then your code works just as expected:

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (let i = 0; i < nums.length; i++) {
    smallest_index = find_smallest(nums);
    arr.push("5");
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

console.log(sortArray(nums));

The only difference is using

for (let i = 1; ...

instead of

for (i = 1; ...

Upvotes: 1

Related Questions