Min Array Value Based on Function

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the minBy function in JavaScript. The minBy function returns the minimum value of an array, based on a function that maps each element to a value. Through this lab, you will learn how to use minBy to find the minimum value of an array, using a provided function.


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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/data_types -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/arith_ops -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/comp_ops -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/array_methods -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/higher_funcs -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/destr_assign -.-> lab-28331{{"`Min Array Value Based on Function`"}} javascript/spread_rest -.-> lab-28331{{"`Min Array Value Based on Function`"}} end

Function to Return Minimum Value of an Array

To start practicing coding, open the Terminal/SSH and type node.

This function returns the minimum value of an array, based on the provided function.

To do this, it uses Array.prototype.map() to map each element to the value returned by the function. It then uses Math.min() to get the minimum value.

const minBy = (arr, fn) =>
  Math.min(...arr.map(typeof fn === "function" ? fn : (val) => val[fn]));

You can use this function by passing an array and a function. For example:

minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], (x) => x.n); // 2
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"); // 2

Summary

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

Other JavaScript Tutorials you may like