I'm trying to write a function decreasingOrder
which takes a positive integer as input and return an array
of its digits in decreasing order.
e.g., decreasingOrder(1234)
Should give [4,3,2,1]
.
function decreasingOrder(n) {
let unarr = [...`${n}`].map(i => parseInt(i)); //Unordered Array of Digits
let oarr = []; //Ordered Array of Digits
for(let j=0; j<unarr.length; j++){
let max = Math.max.apply(Math, unarr);
oarr.push(max);
unarr.splice(unarr.indexOf(max), 1); //delete element from array
}
return oarr;
}
console.log(decreasingOrder(1234));
//Expected [4,3,2,1], Instead got [4,3]
splice
method also reduces the number
of iteration.delete
operator but get [4, NaN, NaN, NaN]
(because Math.max([undefined])
).unarr.length
in condition
expression for for
loop, it works fine!So when I use splice
method to delete elements it reduces the unarr.length
and when I tried to keep unarr.length
constant using delete
operator it gives NaN
, what should I do? Is there any other way to write to the same function? I'm beginner in JavaScript.
The issue in your code is unarr.splice(unarr.indexOf(max), 1)
inside loop.
By taking your example of
console.log(decreasingOrder(1234))
. In the first cycle the highest number from the array is found and is removed from the array and pushed to new array.
At the end of the first cycle the outputs will be
unarr = [1, 2, 3]
,oarr = [4]
andj=1
Likewise after second loop
unarr = [1, 2]
,oarr = [4, 3]
andj=2
. Now the loop conditionj < unarr.length
is not satisfied hence the loop breaks. So the output will be[4, 3]
.
Instead you can use the below utility for your requirement.
function decreasingOrder(n) {
let unarr = [...`${n}`].map(i => parseInt(i)) //Unordered Array of Digits
return unarr.sort((a,b) => b-a)
}
console.log(decreasingOrder(1234))
Hope this helps.