Tell us what’s happening:
Describe your issue in detail here.
I wanted to see a more efficient solution and one that actually utilized the “forming” rule: where if the symbol appears before a larger symbol its subtracted (example: IV = V − I = 5 − 1 = 4).
**Your code so far**
function convertToRoman(num) {
const numerals = {
1000:'M',
900:'CM',
500:'D',
400:'CD',
100:'C',
90:'XC',
50:'L',
40:'XL',
10:'X',
9:'IX',
5:'V',
4:'IV',
1:'I'
}
let split = splitNumber(num);
let numArr = Object.keys(numerals).sort((a,b)=> a+b);
let str = '';
let str2=[]
//console.log(numArr)
//start looping
for (let i = 0; i < split.length; i++){
let r = split[i];
for(let j = 0; j < numArr.length ; j++){
//console.log(j)
while(r >= numArr[j]){
r -= numArr[j];
//console.log(numerals[numArr[j]].toString())
str = str.concat(numerals[numArr[j]]);
//str2.push(numerals[numArr[j]])
}
}
}
console.log(str)
return str;
}
const splitNumber = (num, arr = [], m = 1) => {
if(num){
//console.log(m)
return splitNumber(Math.floor(num / 10), [m * (num % 10)].concat(arr), m * 10);
}
return arr;
};
convertToRoman(900);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0
It shouldn’t working either browser. Sort by default sorts the values as if they are strings. woops, that part isn’t the issue. The sort function is bad.
You are intending to make an array of strings out of numbers by sorting on their sum? Why?!?!
The typical way to compare numbers is with their difference.
Ah, see what is happening. Key order isn’t specified for any implementation. You are accidentally doing no sort, just a reverse of whatever order is present, and it just so happens that in some browsers the keys are already in the right order for this to work.
By default it does not do numerically ascending order. It does lexographic ascending order.
To use numerically ascending, use the sort function in the docs. For numerically descending, multiply that value by -1 (flip the order in the operation used).
<:O , that makes sense, in the beginning I just assumed that the object wouldn’t do any numerical or lexographic sorting and just place the key-pair values in the same fashion that I wrote it out as.