Index Array Based on Function

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the indexBy function in JavaScript, which creates an object from an array based on a provided function. The purpose of this lab is to help you understand how to use Array.prototype.reduce() and how to apply a function to each value of an array to produce a key-value pair. By the end of this lab, you will be able to use indexBy to map values of an array to keys and create a new object.


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`") subgraph Lab Skills javascript/variables -.-> lab-28327{{"`Index Array Based on Function`"}} javascript/data_types -.-> lab-28327{{"`Index Array Based on Function`"}} javascript/arith_ops -.-> lab-28327{{"`Index Array Based on Function`"}} javascript/comp_ops -.-> lab-28327{{"`Index Array Based on Function`"}} javascript/higher_funcs -.-> lab-28327{{"`Index Array Based on Function`"}} end

Function to Index an Array

To index an array using a function, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.reduce() to create an object from the array.
  3. Apply the provided function to each value of the array to produce a key and add the key-value pair to the object.

Here's an example code snippet:

const indexBy = (arr, fn) =>
  arr.reduce((obj, v, i) => {
    obj[fn(v, i, arr)] = v;
    return obj;
  }, {});

You can use this function as follows:

indexBy(
  [
    { id: 10, name: "apple" },
    { id: 20, name: "orange" }
  ],
  (x) => x.id
);
// { '10': { id: 10, name: 'apple' }, '20': { id: 20, name: 'orange' } }

This function creates an object from an array by mapping each value to a key using a provided function. The resulting object contains key-value pairs where the keys are produced by the function and the values are the original array elements.

Summary

Congratulations! You have completed the Index Array Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like