_.minBy(array, [iteratee=_.identity])
182
_.minBy(array, [iteratee=_.identity])
_.minBy此方法类似min,区别是接收一个iteratee为每一个数组元素调用去根据每个值的排列生成对应的标准值
参数
array (Array): 需要被迭代的数组
[iteratee=_.identity] (Function): 对每一个元素调用生成标准值的迭代器函数
返回值
(*): 返回数组最小值
例子
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } // The `_.property` iteratee shorthand. _.minBy(objects, 'n'); // => { 'n': 1 }
源代码
import isSymbol from './isSymbol.js' /** * This method is like `min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * const objects = [{ 'n': 1 }, { 'n': 2 }] * * minBy(objects, ({ n }) => n) * // => { 'n': 1 } */ //此方法类似min,区别是接收一个iteratee为每一个数组元素调用去根据每个值的排列生成对应的标准值 function minBy(array, iteratee) { let result//最小值结果 if (array == null) {//如果数组为null,返回undefined return result } for (const value of array) {//循环数组 let computed//中间变量存下当前最小值的标准值 const current = iteratee(value)//当前循环元素的标准值 if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : (current < computed) )) { //如果current不是null且computed还没有值,并且current不是NaN且不是Symbol对象,就创建computed和result存下当前current //否则就用comparator比较current和computed的大小 computed = current result = value } } return result } export default minBy