Created
September 16, 2018 23:48
-
-
Save cefaijustin/5114d315a1b4e1775a2bdfc882194e1a to your computer and use it in GitHub Desktop.
Find the sum of all elements in an array consisting of strings and numbers.
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
function addElements(arr) { | |
// create an array of the alphabet to find the numerical value of each letter in the input array | |
let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", | |
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", | |
"v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", | |
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", | |
"T", "U", "V", "W", "X", "Y", "Z"]; | |
let nums = []; // <---- empty array to store the numbers from the input | |
let strings = []; // <---- empty array to store the strings from the input | |
let letterTotal = 0; | |
for (let i = 0; i < arr.length; i ++) { // <---- loop through the input array | |
if (isNaN(arr[i])) { // <---- if the index is not a number | |
strings.push(arr[i]) // <---- push it into the strings array | |
} else { | |
nums.push(arr[i]) // <---- otherwise push it into the numbers array | |
} | |
} | |
nums = nums.reduce((a, b) => a + b, 0); // <---- use .reduce to add all elements in the numbers array | |
strings = strings.toString().split(""); // <---- call the toString method on the strings array, then split it by each letter | |
strings.forEach( i => { // <---- loop through both the strings array and alphabet | |
alphabet.forEach( j => { | |
if (i === j) { // <---- if the letter from the string matches the letter from the alphabet - | |
letterTotal += alphabet.indexOf(i) + 1; // <---- add the index of that letter to the letter total | |
} // <---- since arrays are zero indexed, we add one to each number | |
}) | |
}) | |
console.log(letterTotal + nums); // finally, concatenate both totals and display the result | |
} | |
addElements([1, 'all', 4, 53, 'Cats', 24, 'Bilbo Swaggins', 12, 74, 'Wowwie', 23, 60, 13, 46, 'That is amazing']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment