Alphabetizing Arrays, Objects, and Arrays of Objects
An array: let fruits = [`bananas`, `Apples`, `Oranges`]; You can sort of alphabetize that as easy as: fruits.sort(); But notice the inconsistent casing in the array... uppercase characters will all be...
View ArticleConvert Polygon to Path Data
I've had to do this a few times recently so I thought I'd save the method. StackOverflow has a method that works great: [].forEach.call(polys,convertPolyToPath); function convertPolyToPath(poly){ var...
View ArticleSelect Random Item from an Array
var myArray = [ "Apples", "Bananas", "Pears" ]; var randomItem = myArray[Math.floor(Math.random()*myArray.length)]; (more…)
View ArticleReplacements for setInterval Using requestAnimationFrame
When it comes to animation, we're told that setInterval is a bad idea. Because, for example, the loop will run regardless of anything else going on, rather than politely yielding like...
View ArticleAdd a Number to Two Variables At Once
You can initialize two variables to the same value at once, kinda: var foo, bar; foo = bar = 10; But there is no similarly easy mechanism to add, say, 5 to both foo and bar at the same time. Of course,...
View ArticleAlphabetizing Arrays, Objects, and Arrays of Objects
An array: let fruits = [`bananas`, `Apples`, `Oranges`]; You can sort of alphabetize that as easy as: fruits.sort(); But notice the inconsistent casing in the array... uppercase characters will all be...
View ArticleRemove Duplicates from an Array
Compiled by Svein Petter Gjøby: const array = [1, 1, 1, 3, 3, 2, 2]; // Method 1: Using a Set const unique = [...new Set(array)]; // Method 2: Array.prototype.reduce const unique =...
View ArticleRequired Parameters for Functions in JavaScript
Ooo this is clever! I'm snagging this from David's blog. const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`)...
View ArticleGetting First and Last Items in Array (and splitting all the rest)
I needed to get the first item from an array lately in JavaScript. Hmmmm … lemme think here. I remember that .pop() is for snagging the last item from the array, like this: const arr = ["This",...
View ArticleInject HTML From a String of HTML
Say you have some HTML that is a string: let string_of_html = ` <div>Cool</div> `; Maybe it comes from an API or you've constructed it yourself from template literals or something. You can...
View ArticleThe .classList() API
Assuming you have an element in the DOM: <div id="el"></div> Get a reference to that DOM element: const el = document.querySelector("#el"); Then you can manipulate the classes on that...
View Article