Sum an Array of Numbers with JavaScript / / No Comments It’s rare that I’m disappointed by the JavaScript language not having a function that I need. One such case was summing an array of numbers — I was expecting Math.sum or a likewise, baked in API. Fear not — summing an array of numbers is easy using Array.prototype.reduce! const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((a, b) =a + b, 0); The 0 represents the starting value while with a and b, one represents the running total with the other representing the value to be added. You’ll also note that using reduce prevents side effects! I’d still prefer something like Math.sum(...numbers) but a simple reduce will do! The post Sum an Array of Numbers... more → Posted in: JavaScript Tagged with: Array, JavaScript, numbers
JavaScript Array Group / / No Comments Managing, sorting, and manipulating data with JavaScript is a skill we’ve often delegated to third party libraries like lodash. As the JavaScript language progresses, however, these features eventually get. added to the JavaScript specification. Two such APIs for grouping of Array data are `Array.prototype.group and Array.prototype.groupToMap. Array.prototype.group To group an array of objects by a given property, call the group method with function that returns the grouping string: const teams = [ { name: "Arsenal", origin: "London", tier: "legendary" }, { name: "Manchester United", origin: "Manchester", tier: "legendary" }, { name: "Liverpool", origin: "Liverpool", tier: "legendary"... more → Posted in: JavaScript Tagged with: Array, Group, JavaScript
Get a Random Array Item with JavaScript / / No Comments JavaScript Arrays are probably my favorite primitive in JavaScript. You can do all sorts of awesome things with arrays: get unique values, clone them, empty them, etc. What about getting a random value from an array? To get a random item from an array, you can employ Math.random: const arr = [ "one", "two", "three", "four", "tell", "me", "that", "you", "love", "me", "more" ]; const random1 = arr[(Math.floor(Math.random() * (arr.length)))] const random2 = arr[(Math.floor(Math.random() * (arr.length)))] const random3 = arr[(Math.floor(Math.random() * (arr.length)))] const random4 = arr[(Math.floor(Math.random() * (arr.length)))] console.log(random1,... more → Posted in: JavaScript Tagged with: Array, Item, JavaScript, Random
The ins and outs of JavaScript reducer — a simple, yet powerful array method – The Next Web / / No Comments The ins and outs of JavaScript reducer — a simple, yet powerful array method The Next Web “JavaScript” – Google News… more → Posted in: JavaScript Tagged with: Array, JavaScript, method, Next, outs, powerful, reducer, simple