基于函数的数组最小值

Beginner

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

简介

在本实验中,我们将探索 JavaScript 中的 minBy 函数。minBy 函数根据一个将每个元素映射为一个值的函数,返回数组中的最小值。通过本实验,你将学习如何使用 minBy 以及一个提供的函数来找到数组中的最小值。

返回数组最小值的函数

要开始练习编码,请打开终端/SSH 并输入 node

此函数根据提供的函数返回数组的最小值。

为此,它使用 Array.prototype.map() 将每个元素映射到该函数返回的值。然后使用 Math.min() 来获取最小值。

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

你可以通过传入一个数组和一个函数来使用此函数。例如:

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

总结

恭喜你!你已经完成了基于函数的数组最小值实验。你可以在 LabEx 中练习更多实验来提升你的技能。