Jacob Ruiz

View Original

10 Useful Things You Can Do With Underscore.js

Underscore is a widely used library of Javascript functions that help you do common things quickly and easily. There are a whole bunch of functions that help you manipulate arrays and array-like objects, which I'll focus on here. Read the docs for Underscore.js for more.

flatten

From the docs: Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

See this content in the original post

without

From the docs: Returns a copy of the array with all instances of the values removed.

See this content in the original post

union

From the docs: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

See this content in the original post

intersection

From the docs: Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays

See this content in the original post

difference

From the docs: Similar to without, but returns the values from array that are not present in the other arrays.

See this content in the original post

zip

From the docs: Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

See this content in the original post

unzip

From the docs: The opposite of zip. Given an array of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on.

See this content in the original post

object

From the docs: Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. Passing by pairs is the reverse of pairs. If duplicate keys exist, the last value wins.

See this content in the original post

where

From the docs: Looks through each value in the list, returning an array of all the values that  matches the key-value pairs listed in properties.

See this content in the original post

pluck

From the docs: A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

See this content in the original post