'Write a function which return the digits
Given a varying number of integer arguments, return the digits that are not present in any of them.
Example:
[12, 34, 56, 78] => "09"
[2015, 8, 26] => "3479"
Note: the digits in the resulting string should be sorted.
Help please, how to do this with a short and simple code, which method should I use? RegEx for compare?
function unusedDigits(numbers) {
}
console.log(unusedDigits([12, 34, 56, 78]));
console.log(unusedDigits([2015, 8, 26]));
Solution 1:[1]
First concatenate the numbers into a single string:
> [2015, 8, 26].join('')
'2015826'
Then remove them from '0123456789':
> [...'0123456789'].filter(ch => !'2015826'.includes(ch)).join('')
'3479'
function unusedDigits(numbers) {
const s = numbers.join('');
return [...'0123456789'].filter(ch => !s.includes(ch)).join('');
}
console.log(unusedDigits([12, 34, 56, 78]));
console.log(unusedDigits([2015, 8, 26]));
For a more efficient way if the input is huge, you can create a Set of digits instead of joining into a string.
Solution 2:[2]
You could take a Set and remove unwanted digits.
function unused (array) {
return Array
.from([...array.join('')].reduce(
(s, v) => (s.delete(v), s),
new Set('0123456789')
))
.join('')
}
console.log(unused([12, 34, 56, 78])); // "09"
console.log(unused([2015, 8, 26])); // "3479"
An approach with short circuit
function unused (array) {
const s = new Set('0123456789');
[...array.join('')].every(v => (s.delete(v), s.size));
return Array
.from(s)
.join('')
}
console.log(unused([12, 34, 56, 78])); // "09"
console.log(unused([2015, 8, 26])); // "3479"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dogbert |
| Solution 2 |
