javascriptroom blog

Underscore.js _.pluck Function: A Comprehensive Guide

Underscore.js is a popular JavaScript utility library that provides a wealth of functions to simplify common programming tasks, such as array manipulation, function composition, and object handling. Among its many utilities, _.pluck stands out as a concise and powerful tool for extracting property values from a collection of objects.

Whether you’re working with API responses, datasets, or any array of objects, _.pluck streamlines the process of extracting specific properties (e.g., IDs, names, or emails) into a new array. This blog will dive deep into _.pluck, covering its syntax, use cases, best practices, limitations, and alternatives. By the end, you’ll be equipped to use _.pluck effectively in your projects.

2026-06

Table of Contents#

  1. What is _.pluck?
  2. Syntax and Parameters
  3. Return Value
  4. Basic Example
  5. Advanced Examples
  6. Common Use Cases
  7. Common Practices
  8. Best Practices
  9. Limitations and Edge Cases
  10. Alternatives to _.pluck
  11. Conclusion
  12. References

What is _.pluck?#

_.pluck is a utility function in Underscore.js designed to extract the value of a specific property from each element in a collection (array or object). It iterates over the collection, accesses the specified property for each element, and returns a new array containing these values in the same order as the original collection.

In essence, _.pluck is a specialized version of _.map (Underscore’s iteration function) optimized for the common task of extracting property values. It simplifies code that would otherwise require writing a custom _.map callback to access the property.

Syntax and Parameters#

The syntax for _.pluck is straightforward:

_.pluck(list, propertyName)

Parameters:#

  • list (Array|Object): The collection to iterate over. This can be an array (where elements are objects) or an object (where values are objects; keys are ignored, and iteration is over values).
  • propertyName (String|Number): The name of the property to extract from each element. For arrays of arrays, this can be a numeric index (e.g., 0 to extract the first element of each sub-array).

Return Value#

_.pluck returns a new array containing the values of the specified propertyName from each element in list. If an element does not have the specified property, undefined is included in the result for that element.

Basic Example#

Let’s start with a simple example. Suppose we have an array of user objects, each with name and age properties. We want to extract all name values into a new array:

// Import Underscore.js (assuming it's loaded via CDN or module)
const _ = require('underscore'); // or include via <script> in browsers
 
const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];
 
// Extract the 'name' property from each user
const userNames = _.pluck(users, 'name');
 
console.log(userNames); // Output: ['Alice', 'Bob', 'Charlie']

Here, _.pluck iterates over the users array, accesses the name property of each object, and returns ['Alice', 'Bob', 'Charlie'].

Advanced Examples#

Example 1: Extracting from an Object (Instead of Array)#

_.pluck works with objects too. It iterates over the values of the object (ignoring keys) and extracts the property:

const userData = {
  alice: { id: 1, email: '[email protected]' },
  bob: { id: 2, email: '[email protected]' },
  charlie: { id: 3, email: '[email protected]' }
};
 
// Extract 'email' from each value in userData
const emails = _.pluck(userData, 'email');
 
console.log(emails); // Output: ['[email protected]', '[email protected]', '[email protected]']

Note: The order of values in the result depends on the object’s key insertion order (consistent in ES6+ environments).

Example 2: Extracting from Arrays of Arrays#

If the collection is an array of arrays, use a numeric propertyName to extract elements by index:

const matrix = [
  [10, 20, 30],
  [40, 50, 60],
  [70, 80, 90]
];
 
// Extract the first element (index 0) of each sub-array
const firstColumn = _.pluck(matrix, 0);
 
console.log(firstColumn); // Output: [10, 40, 70]

Example 3: Handling Missing Properties#

If some elements lack the target property, _.pluck returns undefined for those entries:

const products = [
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Mouse' }, // No 'price' property
  { id: 3, name: 'Keyboard', price: 49 }
];
 
const prices = _.pluck(products, 'price');
 
console.log(prices); // Output: [999, undefined, 49]

Common Use Cases#

_.pluck shines in scenarios where you need to quickly extract a single property from a collection. Common use cases include:

  1. Data Extraction: Extracting IDs, names, or emails from API responses (e.g., _.pluck(apiResponse.users, 'id')).
  2. Chart Data Preparation: Extracting x/y values from a dataset for visualization (e.g., _.pluck(salesData, 'revenue')).
  3. Filtering + Extraction: Combining with _.filter to extract properties from a subset of the collection:
    const adults = _.filter(users, user => user.age >= 18);
    const adultNames = _.pluck(adults, 'name'); // Extract names of adults only
  4. Simplifying Reducers: Extracting properties before aggregating data (e.g., summing ages: _.sum(_.pluck(users, 'age'))).

Common Practices#

  • Chaining with Underscore: Use _.chain to combine _.pluck with other Underscore functions for cleaner code:

    const activeUserEmails = _.chain(users)
      .filter(user => user.isActive) // Filter active users
      .pluck('email') // Extract emails
      .value(); // Get the final array
  • Handling Nested Properties (Indirectly): _.pluck does not support nested properties (e.g., user.address.city), but you can use _.map with _.property (another Underscore utility) as a workaround:

    const userCities = _.map(users, _.property('address.city')); 
    // Equivalent to _.pluck for nested properties

Best Practices#

  1. Prefer Readability: Use _.pluck when it makes code more concise than a manual _.map or native Array.map. For example:

    // Good: Concise and readable
    _.pluck(users, 'name');
     
    // Less concise (but equivalent)
    _.map(users, user => user.name);
  2. Beware of undefined Values: If some elements may lack the target property, handle undefined explicitly (e.g., with _.compact to remove undefined entries):

    const validPrices = _.compact(_.pluck(products, 'price')); // Removes undefined
  3. Avoid Overusing for Non-Object Collections: _.pluck is designed for objects. For primitives (e.g., [1, 2, 3]), extracting properties like toString will return function references, not values:

    _.pluck([1, 2, 3], 'toString'); // [Function: toString, Function: toString, Function: toString]
  4. Type Check Inputs: Ensure list is a valid collection (array/object) and propertyName is a string/number to avoid unexpected behavior.

Limitations and Edge Cases#

  • No Nested Property Support: _.pluck('user.address.city') will not work. Use _.map with _.property instead (as shown earlier).
  • Functions as Values: If the property is a function, _.pluck returns the function itself, not its result:
    const items = [{ getValue: () => 42 }, { getValue: () => 99 }];
    _.pluck(items, 'getValue'); // [Function, Function] (not [42, 99])
  • Empty or Non-Collection Inputs: If list is null or undefined, _.pluck returns an empty array:
    _.pluck(null, 'name'); // []
    _.pluck(undefined, 'age'); // []
  • Non-Object Elements: If elements are primitives (e.g., strings, numbers), accessing properties returns undefined (unless the primitive has the property, like 'hello'.length):
    _.pluck(['hello', 'world'], 'length'); // [5, 5] (works for string length)
    _.pluck([123, 456], 'length'); // [undefined, undefined] (numbers have no length)

Alternatives to _.pluck#

With the rise of modern JavaScript (ES6+), native methods and other libraries offer alternatives to _.pluck:

1. Native Array.map#

For arrays, Array.map is a built-in alternative with no external dependencies:

const userNames = users.map(user => user.name); // Equivalent to _.pluck(users, 'name')

2. Lodash’s _.map with _.property#

Lodash (a popular alternative to Underscore) deprecated _.pluck in favor of _.map with _.property:

import { map, property } from 'lodash';
const userNames = map(users, property('name'));

3. Ramda’s pluck#

Ramda, a functional programming library, offers a pluck function with similar behavior:

import { pluck } from 'ramda';
const userNames = pluck('name')(users); // Curried version

Conclusion#

_.pluck is a versatile utility for extracting property values from collections, simplifying code and improving readability. While modern JavaScript and libraries like Lodash offer alternatives, _.pluck remains valuable in Underscore.js codebases for its brevity and focus on the common task of property extraction.

By understanding its syntax, use cases, and limitations, you can leverage _.pluck to write cleaner, more maintainable code when working with arrays and objects.

References#