Your current test is not accurate because it doesn't check if the num2
contains other numbers as well - for example, 9993332
would match as well.
One possibility is to sort the digits, then check that every digit at an index is equal to every digit in the other array:
const toArr = num => [...String(num)].sort();
const check = (num1, num2) => {
const arr1 = toArr(num1);
const arr2 = toArr(num2);
return arr1.length === arr2.length && arr1.every(
(digit, i) => arr2[i] === digit
);
};
console.log(check(3332, 3323));
console.log(check(3332, 9993323));
(Once we get Array.prototype.equals
, the above simplifies to => toArr(num1).equals(toArr(num2)
)
A less computationally expensive way (but harder to read at a glance) would be to turn each number into an object which counts up frequencies, then compare the objects.
const toObj = num => {
const obj = {};
for (const char of String(num)) {
obj[char] = (obj[char] || 0) + 1;
}
return obj;
};
const check = (num1, num2) => {
const entries1 = Object.entries(toObj(num1));
const obj2 = toObj(num2);
return (
entries1.length === Object.keys(obj2).length &&
entries1.every(([key, val]) => obj2[key] === val)
);
};
console.log(check(3332, 3323));
console.log(check(3332, 9993323));