I have a function to sort an array of numbers with radix. If I run the code below and manually create a nested array called sortArr it works.
arr = sortArr.flat();
concats properly and arr stays with a length of 5.
var sortArr = Array.from({length:10},()=>[]);
also works.
However if I create the sortArr through fill, arr = sortArr.flat();
doesn't concat properly, but keeps multiplying arr by 10 until it crashes.
Why is this happening?
function radix(arr) {
var max = mostDigits(arr);
for (let i = 0; i < max; i++) {
var sortArr = [[], [], [], [], [], [], [], [], [], []];
//2nd way var sortArr = new Array(10).fill([]);
for (let j = 0; j < arr.length; j++) {
var num = getDigit(arr[j], i);
sortArr[num].push(arr[j]);
}
arr = sortArr.flat();
}
return arr;
}
function getDigit(num, i) {
return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;
}
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
console.log(radix([23, 567, 89, 12234324, 90]));