--- Day 1: Trebuchet?! ---
Go to page
Part 1 & 2 -- What is the sum of all of the calibration values?
const data = $0.innerText.split('\n').slice(0, -1);
let sum = 0;
let str;
let nums = "";
let calibration = [];
data.forEach((item) => {
str = item.replace(/\D/g, '');
str = str[0] + str[str.length-1];
sum += parseInt(str);
});
console.log(`The sum of all the calibration values for part 1 is ${sum}`);
// Reset variables
sum = 0;
str = "";
data.forEach((item) => {
for (let j = 0; j < item.length; j++) {
str += item[j];
str = checkNum(str);
}
str = nums[0] + nums[nums.length-1];
sum += parseInt(str);
nums = "";
});
console.log(`The sum of all the calibration values for part 2 is ${sum}`);
function checkNum(str) {
const numArray = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
if (!isNaN(str.slice(-1))) {
nums += str.slice(-1);
str = "";
} else {
numArray.forEach((word, index) => {
if (str.includes(word)) {
nums += (index + 1).toString();
str = str.slice(-1);
}
});
}
return str;
}
Language:JavaScript