Skip to content

Instantly share code, notes, and snippets.

@sysoev-dev
Last active May 9, 2024 09:33
Show Gist options
  • Save sysoev-dev/2cdad37813a29fadc1a31af8580b86d8 to your computer and use it in GitHub Desktop.
Save sysoev-dev/2cdad37813a29fadc1a31af8580b86d8 to your computer and use it in GitHub Desktop.
function extractNum(str) {
const match = str.match(/\d+/);
return parseInt(match[0], 10);
}
function calcSum(arr) {
const flatArr = arr.flat(2);
let sum = 0;
flatArr.forEach((item) => {
if (typeof item === "string") {
sum += extractNum(item);
} else {
sum += item;
}
});
return sum;
}
console.log(calcSum([1, 2, "3x"]));
console.log(calcSum([1, 2, "x3"]));
console.log(calcSum([1, [1, [2]], 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment