Last active
April 2, 2024 16:04
-
-
Save AngeloAnolin/8d907b85382d15d2ddbbe62d26be197e to your computer and use it in GitHub Desktop.
Add array values if digits does not contain any repeating number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const uniqueSum = (arr: number[]) => { | |
// Filter any number from the array that has repeating digits | |
const filterRepeatingDigits = (num: number) => { | |
const digits = num.toString().split(''); | |
return digits.length === new Set(digits).size; | |
} | |
// Obtain an array of numbers containing only numbers w/ non-repeating digits | |
const filtered = arr.filter(filterRepeatingDigits) | |
// Use reduce to get the sum. Initial value of 0 is provided in case the filtered array returns empty | |
return filtered.reduce((a,b)=> a+b, 0); | |
} | |
const arr0 = uniqueSum([1, 2, 3]); // 6 | |
const arr1 = uniqueSum([11, 22, 33]); // 0 | |
const arr2 = uniqueSum([101, 2, 3]); // 5 | |
const arr3 = uniqueSum([11, 22, 33, 440, 56]); // 56 | |
console.log(arr0) | |
console.log(arr1) | |
console.log(arr2) | |
console.log(arr3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment