Home > front end >  Trying to sort array without sort() in JavaScript
Trying to sort array without sort() in JavaScript

Time:09-11

// sorting an array

const least_num = (arr)=>{
  let smallest = arr[0];
  let smallest_index = 0;
  for(let i=1; i<arr.length;i  ){
    if (arr[i] < smallest) {
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index
}


const sortArray = (arr)=>{
 const newArr = [];
 for(let i in arr){
  let smallest = least_num(arr);
  console.log(smallest,i)
  console.log(arr.splice(smallest,1),arr)
 }
 return newArr;

}

console.log(sortArray([5,4,3,2,1]));

I am trying to sort array without sort(). It stuck at array length of 2. It may because of for loop. And how to remove element in a array using index.

CodePudding user response:

A few issues:

  • The code never adds anything to newArr, so the function always returns an empty array. It should add the removed (spliced) element to newArr. This can be done with newArr.push(...arr.splice(smallest,1))

  • The for..in loop will iterate fewer times than expected, because in each iteration the array gets shorter, thereby removing future iterations for the loop. As the idea is to remove all items from the array, just keep looping until the array is empty with while (arr.length)

With these two corrections, your code works:

const least_num = (arr)=>{
  let smallest = arr[0];
  let smallest_index = 0;
  for(let i=1; i<arr.length;i  ){
    if (arr[i] < smallest) {
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index
}


const sortArray = (arr)=>{
    const newArr = [];
    while(arr.length) {
        let smallest = least_num(arr);
        console.log(smallest)
        newArr.push(...arr.splice(smallest,1));
        console.log(arr)
    }
    return newArr;
}

console.log(sortArray([5,4,3,2,1]));

  • Related