Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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; ...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!