Map Array to Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will learn how to map the values of an array to an object using a function in JavaScript. The lab will walk you through the process of using Array.prototype.reduce() to apply a function to each element in an array and combine the results into an object. You will also learn how to use the element as the key and the result of the function as the value for each property.


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-28478{{"`Map Array to Object`"}} javascript/data_types -.-> lab-28478{{"`Map Array to Object`"}} javascript/arith_ops -.-> lab-28478{{"`Map Array to Object`"}} javascript/comp_ops -.-> lab-28478{{"`Map Array to Object`"}} javascript/array_methods -.-> lab-28478{{"`Map Array to Object`"}} javascript/higher_funcs -.-> lab-28478{{"`Map Array to Object`"}} javascript/destr_assign -.-> lab-28478{{"`Map Array to Object`"}} end

Mapping Array to Object

To map the values of an array to an object using a function, follow these steps:

  1. Open the Terminal/SSH and type node to start coding practice.
  2. Use Array.prototype.reduce() to apply fn to each element in arr and combine the results into an object.
  3. Use el as the key for each property and the result of fn as the value.

Here is an example code snippet:

const mapObject = (arr, fn) =>
  arr.reduce((acc, el, i) => {
    acc[el] = fn(el, i, arr);
    return acc;
  }, {});

You can use the mapObject function as shown in this example:

mapObject([1, 2, 3], (a) => a * a); // { 1: 1, 2: 4, 3: 9 }

Summary

Congratulations! You have completed the Map Array to Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like