You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript或Lodash获取多个数组的共同最小值与最大值

实现方法

我们需要先找出三个数组的共同元素(交集),再从这些共同元素中提取最小值和最大值。以下是原生JavaScript和Lodash两种实现方案:

原生JavaScript 实现

const arrayA = [5.2, 3, 3.5, 2.7, 3.3, 5, 2.9];
const arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9];
const arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4];

// 1. 求三个数组的交集
const setA = new Set(arrayA);
const setB = new Set(arrayB);
const commonElements = arrayC.filter(num => setA.has(num) && setB.has(num));
// 去重(可选,极值计算不受重复元素影响)
const uniqueCommon = [...new Set(commonElements)];

// 2. 计算交集的最小/最大值
const commonMin = Math.min(...uniqueCommon);
const commonMax = Math.max(...uniqueCommon);

console.log('共同最小值:', commonMin); // 输出 2.7
console.log('共同最大值:', commonMax); // 输出 3.3

Lodash 实现

先确保已引入Lodash库(Node.js环境用const _ = require('lodash'),浏览器环境可通过CDN引入):

const arrayA = [5.2, 3, 3.5, 2.7, 3.3, 5, 2.9];
const arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9];
const arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4];

// 1. 用Lodash的intersection方法求交集(自动去重)
const commonElements = _.intersection(arrayA, arrayB, arrayC);

// 2. 计算最小/最大值
const commonMin = _.min(commonElements);
const commonMax = _.max(commonElements);

console.log('共同最小值:', commonMin); // 输出 2.7
console.log('共同最大值:', commonMax); // 输出 3.3

内容的提问来源于stack exchange,提问作者hotcakedev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:32:09