-2

I need a function that will take an array of numbers, and which will return an array that only retains the numbers that are unique in their digit sequence, i.e. that only occur once even if you would reverse their digits.

This is my code so far:

var a=[5,8,3,8,3,7,5,12,21];
console.log(a);
let output=[...new Set([...a])]  // it removes the repeated data...
console.log(output);

This works for the numbers 3, 8 and 5, whose duplicates are removed, but the value 21 should also be removed, because there is already 12, which is 21 with the digits in reversed order.

How can I achieve that?

The expected output for the above example is:

[5,8,3,7,12]

My code returns:

[5,8,3,7,12,21]
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    *"i want to remove 21"*: what is holding you back to do that? In the code you have given there is no attempt to do that... – trincot Aug 13 '22 at 14:50

2 Answers2

0

You need (of course) to include the logic of reversing digits in a number.

I will assume that when the rightmost digit of a number is 0, that the reversal of that number is not defined. So the reversal of 19 is 91, but the reversal of 190 is not 91, but undefined (or NaN).

First define a function for that reversal of digits, and then use the idea of building a set:

function reverseDigits(num) {
    // A Number should not have 0 as first digit
    //    unless it is 0
    if (num && num % 10 == 0) return NaN; 
    return +[...String(num)].reverse().join("");
}

function specialUnique(a) {
    const set = new Set;
    for (const value of a) {
        if (!set.has(value) && !set.has(reverseDigits(value))) {
            set.add(value);
        }
    }
    return [...set];
} 

// Example input
const a = [5,8,3,8,3,7,5,12,21];
const output = specialUnique(a);
console.log(output);
trincot
  • 317,000
  • 35
  • 244
  • 286
-1

You can use the filter.

let valueToRemove = 21;

output = output.filter((item) => item !== valueToRemove);
Deyan Petrov
  • 150
  • 4