Output:
Advent of Code day 1 part 1
let filteredData = data.split("\n").filter(bit => bit !== null && bit !== "")
let tempVal = ""
let total = 0
for (let line of filteredData) {
for (let char of line.split("")) {
if (/\d/.test(char)) {
tempVal += char
break
}
}
for (let char of line.split("").reverse()) {
if (/\d/.test(char)) {
tempVal += char
break
}
}
console.log(tempVal)
total += parseInt(tempVal, 10)
tempVal = ""
}
return total
Small explanation: First, I split the data into each line and cleared all null values (i.e. empty values). Then, using a for loop, I went through each line and split that into characters. Then, I looped through each character evaluating if it was a digit and the first digit I found I added to a temporary string and then used break to escape the first for loop. Then I started on the second where I did the same thing, but just backwards using the .reverse() method. Then, I added the number I found to total (having to parse it to an int before I can add it as it was a string beforehand)