Array to Flags Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to convert an array of strings into an object mapping to true. We will utilize the powerful Array.prototype.reduce() method to achieve this. By the end of this lab, you will be able to efficiently transform an array of strings into an object with key-value pairs, making it easier to work with data in your JavaScript applications.


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/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28650{{"`Array to Flags Object`"}} javascript/data_types -.-> lab-28650{{"`Array to Flags Object`"}} javascript/arith_ops -.-> lab-28650{{"`Array to Flags Object`"}} javascript/comp_ops -.-> lab-28650{{"`Array to Flags Object`"}} javascript/higher_funcs -.-> lab-28650{{"`Array to Flags Object`"}} javascript/destr_assign -.-> lab-28650{{"`Array to Flags Object`"}} javascript/spread_rest -.-> lab-28650{{"`Array to Flags Object`"}} end

Converting Array to Flags Object

If you want to start practicing coding, open the Terminal/SSH and type node.

The following function converts an array of strings into an object that maps to true.

To do this, we use Array.prototype.reduce(). This method converts the array into an object, where each array value serves as a key whose value is set to true.

const flags = (arr) => arr.reduce((acc, str) => ({ ...acc, [str]: true }), {});

Here's an example:

flags(["red", "green"]); // { red: true, green: true }

Summary

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

Other JavaScript Tutorials you may like