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.
Function to Index an Array
To index an array using a function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce()to create an object from the array. - 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.