I want to return a sorted array starting with the minimal value; why doesn't it work? thank you!

function getIndexToIns(arr, num) {
  let index=0;
  let arr2=[];
  arr2.length=arr.length;
  for(let i=0;i<arr.length;i++){
      arr2[i]=arr[0];
     
    for(let j=0;j<arr.length;j++){
      
    if(arr[j]<arr2[i]) {
      arr2[i]=arr[j];
      index=j;
    }
    console.log(arr2);
    console.log(arr);

    }
    arr.splice(index,1);
  }
  return arr2;
}

console.log(getIndexToIns([40,60,22,11,34,2], 50));
[ 40, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 40, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 22, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 11, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 11, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 2, , , , ,  ]
[ 40, 60, 22, 11, 34, 2 ]
[ 2, 40, , , ,  ]
[ 40, 60, 22, 11, 34 ]
[ 2, 40, , , ,  ]
[ 40, 60, 22, 11, 34 ]
[ 2, 22, , , ,  ]
[ 40, 60, 22, 11, 34 ]
[ 2, 11, , , ,  ]
[ 40, 60, 22, 11, 34 ]
[ 2, 11, , , ,  ]
[ 40, 60, 22, 11, 34 ]
[ 2, 11, 40, , ,  ]
[ 40, 60, 22, 34 ]
[ 2, 11, 40, , ,  ]
[ 40, 60, 22, 34 ]
[ 2, 11, 22, , ,  ]
[ 40, 60, 22, 34 ]
[ 2, 11, 22, , ,  ]
[ 40, 60, 22, 34 ]
[ 2, 11, 22, , ,  ]

Hi,

I don’t really understand your question. Can you be more explicit?

i want to take an array like this: arr=[4,8,3,2,5,3] and return [2,3,3,4,5,8]; i want to sort an array in ascending order; ignore the num argument;

there is a sort method. pretty simple

As suggested above by @prayamajhi85, you can use the sort method like,

  const sortedArray = arr.sort((a , b) =>   a - b)

You can use .sort() method as suggested above. If you are not comfortable with ES6+ syntax use this instead:

function sortArr(arr) { 
  arr.sort(a, b) {
  return a - b 
}
return arr
}

But as I see your code, it seems to me that you’re implementing bubble sort. If you want to stick on that, have a look here to resolve your issue.

1 Like