Array Element Grouping with Functions

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will learn how to group elements of an array based on a given function using JavaScript. We will make use of Array.prototype.map() and Array.prototype.reduce() to create an object where the keys are produced from the mapped results. By the end of this lab, you will have a solid understanding of how to group and categorize data 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`") subgraph Lab Skills javascript/variables -.-> lab-28325{{"`Array Element Grouping with Functions`"}} javascript/data_types -.-> lab-28325{{"`Array Element Grouping with Functions`"}} javascript/arith_ops -.-> lab-28325{{"`Array Element Grouping with Functions`"}} javascript/comp_ops -.-> lab-28325{{"`Array Element Grouping with Functions`"}} javascript/array_methods -.-> lab-28325{{"`Array Element Grouping with Functions`"}} javascript/higher_funcs -.-> lab-28325{{"`Array Element Grouping with Functions`"}} end

How to Group Array Elements

If you want to practice coding, you can start by opening the Terminal/SSH and typing node. Once you're ready, you can group the elements of an array based on a given function using the following steps:

  1. Use Array.prototype.map() to map the values of the array to a function or property name.
  2. Use Array.prototype.reduce() to create an object where the keys are produced from the mapped results.

Here's an example code snippet:

const groupBy = (arr, fn) =>
  arr
    .map(typeof fn === "function" ? fn : (val) => val[fn])
    .reduce((acc, val, i) => {
      acc[val] = (acc[val] || []).concat(arr[i]);
      return acc;
    }, {});

To test the code, you can use the following examples:

groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}
groupBy(["one", "two", "three"], "length"); // {3: ['one', 'two'], 5: ['three']}

These will return objects with keys based on the specified function and values that are arrays of the original elements that match the function.

Summary

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

Other JavaScript Tutorials you may like