Pluck Values From Array of Objects

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be working on a JavaScript programming exercise that involves extracting values from an array of objects. Specifically, we will be writing a function that takes in an array of objects and a key and returns an array of values corresponding to that key. This exercise will help improve your understanding of functional programming concepts and array manipulation in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/data_types -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/arith_ops -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/comp_ops -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/array_methods -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/higher_funcs -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} javascript/destr_assign -.-> lab-28547{{"`Pluck Values From Array of Objects`"}} end

Instructions to Pluck Values From an Array of Objects

To pluck values from an array of objects, you can follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.map() to map the array of objects to the value of a specified key for each object.
  3. Implement the following function:
const pluck = (arr, key) => arr.map((i) => i[key]);
  1. Test the function with an example array of objects:
const simpsons = [
  { name: "lisa", age: 8 },
  { name: "homer", age: 36 },
  { name: "marge", age: 34 },
  { name: "bart", age: 10 }
];
pluck(simpsons, "age"); // [8, 36, 34, 10]

This will return an array of values corresponding to the specified key from the array of objects.

Summary

Congratulations! You have completed the Pluck Values From Array of Objects lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like