Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elements are getting omitted from Javascript array – problem

I want to sort an array from lowest number to highest. But when I execute the following code, some of my array elements get missed! I don’t know why. I need help.`// Sort an array from lowest to highest

function findSmallest(numArr) {
  let smallestNumber = numArr[0]

  for (let i = 0; i < numArr.length; i++) {
    if (numArr[i + 1] < smallestNumber) {
      smallestNumber = numArr[i + 1]
    }
  }
  return smallestNumber;
}

function getSortedArray(arr) {
  let sortedArray = []


  for (j = 0; j < arr.length; j++) {
    let smallest = findSmallest(arr)
    let smallestNumbmerIndex;

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === smallest) {
        smallestNumbmerIndex = i
      }
    }
    arr.splice(smallestNumbmerIndex, 1)
    sortedArray.push(smallest)
  }

  return sortedArray
}

let myArr = [23, 2, 12, 4]
console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omitted

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

since arr shrinks in each iteration, your for loop won’t run 4 iterations, only 2 –

use while(arr.length){ instead of the for j loop

function findSmallest(numArr) {
  let smallestNumber = numArr[0]

  for (let i = 0; i < numArr.length; i++) {
    if (numArr[i + 1] < smallestNumber) {
      smallestNumber = numArr[i + 1]
    }
  }
  return smallestNumber;
}

function getSortedArray(arr) {
  let sortedArray = []


  while(arr.length) {
    let smallest = findSmallest(arr)
    let smallestNumbmerIndex;

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === smallest) {
        smallestNumbmerIndex = i
      }
    }
    arr.splice(smallestNumbmerIndex, 1)
    sortedArray.push(smallest)
  }

  return sortedArray
}

let myArr = [23, 2, 12, 4]
console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omitted
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading