Created
August 26, 2016 02:16
-
-
Save dela3499/5f5fbc615735436fcee8c48a7c44ddb6 to your computer and use it in GitHub Desktop.
How to convert strings to integers in JavaScript, and sum the values in an array
This file contains hidden or 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
// Convert string to number | |
string = '12.1'; | |
number = parseFloat(string); | |
// Convert float to int | |
myInt = Math.floor(number); | |
// Convert list of strings to list of ints | |
strings = ['1.1','2.1','3.1']; | |
numbers = strings.map(parseFloat); | |
ints = numbers.map(Math.floor); | |
// Sum the list of integers | |
add = function (a, b) { return a + b; }; | |
intSum1 = ints.reduce(add, 0); | |
// Sum list of integers in a general way | |
sum = function (xs) { | |
return xs.reduce(add, 0); | |
} | |
intSum2 = sum(ints); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment