Keith

Underscore JS Library Playground

by Keith Rowles • 20/10/2023JavaScript

Green Blue Manilla Folders

Summary

Playing around with the underscore js library to test out the useful functions and helpers.

Just listed a few examples below.

Setup

Include the cdn link in the head of your html document.

<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.2/underscore-umd-min.js"></script>

Lets define a few arrays.

let numberArray = [1, 2, 3, 4, 5, 6, 7, 300, 222, 345];

let nameArray = ['keith', 'bob', 'tom', 'kelly', 'frank'];

let mixedArray = [
  2,
  'chips',
  'hot dogs',
  345,
  'candy canes',
  'frank',
  'bob',
  7,
];

let students = [
  {
    firstname: 'Mary',
    lastname: 'Jane',
    id: '1',
  },
  {
    firstname: 'John',
    lastname: 'Doe',
    id: '2',
  },
  {
    firstname: 'Frank',
    lastname: 'Spenser',
    id: '13',
  },
];

first

Returns the first element of an array. Passing n will return the first n elements of the array.

_.first(nameArray, 2);
keith,bob

initial

Returns everything but the last entry of the array. Pass n to exclude the last n elements from the result.

_.initial(numberArray, 2);
1,2,3,4,5,6,7,300

last

Returns the last element of an array. Passing n will return the last n elements of the array.

_.last(numberArray);
345

rest

Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

_.rest(nameArray, 2);
tom,kelly,frank

without

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

_.without(nameArray, 'bob');
keith,tom,kelly,frank

intersection

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.

_.intersection(numberArray, mixedArray);
2,7,345

pick

_.pick(students[0], 'lastname').lastname;
Jane

keys

Retrieve all the names of the object’s own enumerable properties.

_.keys(students[0]);
firstname,lastname,id

values

Return all of the values of the object’s own properties.

_.values(students[2]);
Frank,Spenser,13

each

Iterates over a list of elements.

_.each(numberArray, function (element, index) {
  var res = index + ' : ' + element + ' ' + '<br>';
  each.innerHTML += res;
});
0: 1 1: 2 2: 3 3: 4 4: 5 5: 6 6: 7 7: 300 8: 222 9: 345

map

Produces a new array of values by mapping each value in list through a transformation function.

var halfNumbers = _.map(numberArray, function (value, index, items) {
  return value / 2;
});
0.5,1,1.5,2,2.5,3,3.5,150,111,172.5

reduce

Reduce boils down a list of values into a single value.

var sum = _.reduce(
  [1, 2, 3],
  function (memo, num) {
    return memo + num;
  },
  0
);
6

filter

Looks through each value in the list, returning an array of all the values that pass a truth test.

var isEven = _.filter([1, 2, 3, 4, 5, 6], function (number) {
  return number % 2 == 0;
});
2,4,6

Underscore JS Website

Link to Underscore Website