-1
// 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.

ram Kumar
  • 13
  • 1
  • Maybe https://stackoverflow.com/questions/5002848/how-to-define-custom-sort-function-in-javascript can help you? – stijnb1234 Sep 11 '22 at 14:32
  • `arr` is modified during the `for` loop because of [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). Try with `slice` instead. – Louys Patrice Bessette Sep 11 '22 at 14:45

2 Answers2

1

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]));
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can also try this.

const sortArray = (arr)=>{
    let originalArr = [...arr];
    var sortArr = [];
    while(originalArr.length) {
        let val = originalArr[0];
        for ( let j = 1; j < originalArr.length; j++ ) {
            if(val>originalArr[j]) {
                val = originalArr[j];
            }
        }
        sortArr.push(originalArr.splice(originalArr.indexOf(val), 1)[0]);
    }
    return sortArr;
}
console.log(sortArray([5,4,3,2,1]));
shekhar kumar
  • 61
  • 1
  • 5