Group Array Into Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to group an array into an object using JavaScript. Specifically, we will use the Array.prototype.reduce() method to associate properties to values in an object, given an array of valid property identifiers and an array of values. We will also learn how to handle cases where the length of the two arrays differ. By the end of the lab, you will have gained a deeper understanding of how to manipulate objects and arrays 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-28368{{"`Group Array Into Object`"}} javascript/data_types -.-> lab-28368{{"`Group Array Into Object`"}} javascript/arith_ops -.-> lab-28368{{"`Group Array Into Object`"}} javascript/comp_ops -.-> lab-28368{{"`Group Array Into Object`"}} javascript/array_methods -.-> lab-28368{{"`Group Array Into Object`"}} javascript/higher_funcs -.-> lab-28368{{"`Group Array Into Object`"}} javascript/destr_assign -.-> lab-28368{{"`Group Array Into Object`"}} end

How to Group an Array into an Object

To group an array into an object, follow these steps:

  1. Open the Terminal or SSH and type node to start practicing coding.
  2. Use the Array.prototype.reduce() method to build an object from the two arrays.
  3. Provide an array of valid property identifiers and an array of values.
  4. If the length of the property array is longer than the value array, the remaining keys will be set to undefined.
  5. If the length of the value array is longer than the property array, the remaining values will be ignored.

Here is an example code snippet that demonstrates how to group an array into an object:

const zipObject = (props, values) =>
  props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});

zipObject(["a", "b", "c"], [1, 2]); // {a: 1, b: 2, c: undefined}
zipObject(["a", "b"], [1, 2, 3]); // {a: 1, b: 2}

Summary

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

Other JavaScript Tutorials you may like