Flattening an array means making it one-dimensional. The easiest way to flatten an array is via Array.prototype.flat. For many years, doing this in javascript required the use of concat, spread, or reduce. Not anymore. Flatten with Array.prototype.flat This method does exactly what you’d expect: By default, flat only flattens one level deep: But flat accepts […]
Arrays
Javascript map function
The javascript map() function takes in a callback function, applies that callback function to each element of an array, and returns a new array containing the results. Many languages have a map function, and they all behave roughly this way. Javascript map basics map() accepts a single callback function, and passes each element of the […]
Javascript forEach
Javascript’s forEach method is one of its basic array methods, and it’s used all the time. It does as its name suggests, and performs a function for each element of an array: In the function above, I only accessed one argument, item. However, forEach actually makes 3 arguments available to its callback function if you […]
Find elements in a ruby array
There are several ways to do this, and their outputs differ based on your needs Let’s do a couple of examples. Array.include? Simple: Array.index This method is a bit confusingly named. It gives you the first index at which the given element appears, not the element at the index given. Array.find and Array.detect Two names […]
Insert into javascript array at a specific index
There are two options when inserting into an array in javascript: slice() and splice(). Array.prototype.slice Array.prototype.slice returns a copy of a portion of an array, like so: Let’s say we want to insert c where it belongs in this list, between b and d. The three dots … in the above example are known as javascript spread syntax, […]