const arr = [ { name: 'ceshi1', value1: 345, value2: 85934 }, { name: 'ceshi2', value1: 3432, value2: 343432 }, ]; const result = Math.max( ...arr.map(obj => obj.value1), ...arr.map(obj => obj.value2) );找出最大值,并能找到最大值的那个对象
时间: 2023-11-27 16:04:12 浏览: 32
可以先使用 `Math.max` 函数找出数组中所有元素的最大值,然后再遍历一遍数组,找到包含该最大值的对象即可。
代码实现如下:
```javascript
const arr = [
{ name: 'ceshi1', value1: 345, value2: 85934 },
{ name: 'ceshi2', value1: 3432, value2: 343432 },
];
const maxVal = Math.max(
...arr.map(obj => obj.value1),
...arr.map(obj => obj.value2)
);
const result = arr.find(obj => obj.value1 === maxVal || obj.value2 === maxVal);
console.log(result); // 输出 { name: 'ceshi1', value1: 345, value2: 85934 }
```
相关问题
找出const arr = [ { name: 'ceshi1', value1: 345, value2: 85934 }, { name: 'ceshi2', value1: 3432, value2: 343432 }, ];的最大值
这个数组中有两个对象,每个对象有两个属性:value1和value2。如果你要求的是整个数组(包括两个对象)的最大值,那么可以使用以下代码:
```
const arr = [
{ name: 'ceshi1', value1: 345, value2: 85934 },
{ name: 'ceshi2', value1: 3432, value2: 343432 },
];
const result = Math.max(
...arr.map(obj => obj.value1),
...arr.map(obj => obj.value2)
);
console.log(result); // 输出 343432
```
这里使用了`Math.max()`函数来获取一组数字的最大值。我们使用了ES6的展开运算符`...`将两个`map()`函数的结果展开为一组数字,再将这组数字作为参数传递给`Math.max()`函数。
const arr = [ { name: 'ceshi1', value1: 345, value2: 85934 }, { name: 'ceshi2', value1: 3432, value2: 343432 }, ]既能找到最大值,又能找到对象里最大值对的key,用复用性高的方法
可以使用 reduce 方法来实现。具体实现如下:
```javascript
const arr = [
{ name: 'ceshi1', value1: 345, value2: 85934 },
{ name: 'ceshi2', value1: 3432, value2: 343432 },
];
const result = arr.reduce((acc, curr) => {
const maxVal = Math.max(curr.value1, curr.value2);
if (maxVal > acc.maxVal) {
return {
maxVal,
key: Object.keys(curr).find((key) => curr[key] === maxVal),
};
}
return acc;
}, { maxVal: 0, key: '' });
console.log(result); // { maxVal: 343432, key: 'value2' }
```
这段代码中,我们使用了 reduce 方法来对数组进行遍历,并将数组中每个对象中的最大值与当前最大值进行比较,如果当前最大值小于当前对象的最大值,则将当前最大值和对应的 key 更新为当前对象的最大值和对应的 key,最后返回结果。在获取 key 的时候,我们使用了 Object.keys 和 find 方法来获取当前对象中最大值对应的 key。