我正在寻找一种非常快速,干净且高效的方法来获取以下JSON切片中的最大“y”值:
[
{
"x": "8/11/2009",
"y": 0.026572007
},
{
"x": "8/12/2009",
"y": 0.025057454
},
{
"x": "8/13/2009",
"y": 0.024530916
},
{
"x": "8/14/2009",
"y": 0.031004457
}
]
for循环是唯一可行的方法吗?我非常热衷于使用Math.max
。
答案 0 :(得分:540)
要在y
中找到对象的最大array
值:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
答案 1 :(得分:171)
一种方法是使用Array reduce ..
const max = data.reduce(function(prev, current) {
return (prev.y > current.y) ? prev : current
}) //returns object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce(IE9及以上)
如果你不需要支持IE(只有Edge),或者可以使用像Babel这样的预编译器,你可以使用更简洁的语法。
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
答案 2 :(得分:95)
干净简单的ES6(Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
如果arrayToSearchIn
为空,则第二个参数应确保默认值。
答案 3 :(得分:24)
好吧,首先你应该解析JSON字符串,以便你可以轻松访问它的成员:
var arr = $.parseJSON(str);
使用map
方法提取值:
arr = $.map(arr, function(o){ return o.y; });
然后您可以使用max
方法中的数组:
var highest = Math.max.apply(this,arr);
或者作为一个单行:
var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
答案 4 :(得分:20)
我想逐步解释terse accepted answer:
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];
// array.map lets you extract an array of attribute values
var xValues = objects.map(function(o) { return o.x; });
// es6
xValues = Array.from(objects, o => o.x);
// function.apply lets you expand an array argument as individual arguments
// So the following is equivalent to Math.max(3, 1, 2)
// The first argument is "this" but since Math.max doesn't need it, null is fine
var xMax = Math.max.apply(null, xValues);
// es6
xMax = Math.max(...xValues);
// Finally, to find the object that has the maximum x value (note that result is array):
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });
// Altogether
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];
// es6
xMax = Math.max(...Array.from(objects, o => o.x));
maxXObject = objects.find(o => o.x === xMax);
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
&#13;
更多信息:
答案 5 :(得分:9)
这是最短的解决方案(单线) ES6 :
export class DynamicRouteService implements CanActivate {
constructor(private router: Router) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return next.params.pipe(first()).pipe(map(param) => {
console.log(param.id)
return ... // make any API call with param.id and get a response as promise
.then( (response) => {
... // do whatever you want to do on success
return true;
})
.catch( (error) => {
console.error(error);
this.router.navigate(['404']); // route to 404 on failure
return false;
}))
}
}
}
答案 6 :(得分:7)
答案 7 :(得分:7)
var data = [
{ 'name': 'Vins', 'age': 27 },
{ 'name': 'Jan', 'age': 38 },
{ 'name': 'Alex', 'age': 80 },
{ 'name': 'Carl', 'age': 25 },
{ 'name': 'Digi', 'age': 40 }
];
var max = data.reduce(function (prev, current) {
return (prev.age > current.age) ? prev : current
});
//output = {'name': 'Alex', 'age': 80}
答案 8 :(得分:5)
或者简单的排序!保持真实:)
array.sort((a,b)=>a.y<b.y)[0].y
答案 9 :(得分:4)
处理负数大小写(在a
数组中输入)的树 ONELINERS 的比较:
var maxA = Math.max(...a.map(o=>o.y),a[0].y); // 33chars time complexity: >O(2n)
var maxB = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30chars time complexity: O(n)
var maxC = a.sort((a,b)=>b.y-a.y)[0].y; // 27chars time complexity: O(nlogn)
可编辑的示例here。来自maxA,maxB,maxC的想法(副作用:已更改a
-sort
就位)。
var a = [
{"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},
{"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]
var maxA = Math.max(...a.map(o=>o.y),a[0].y);
var maxB = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = a.sort((a,b)=>b.y-a.y)[0].y;
document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
答案 10 :(得分:2)
ES6解决方案
Math.max(...array.map(function(o){return o.y;}))
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
答案 11 :(得分:2)
每个数组并通过Math获得最大值。
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
答案 12 :(得分:1)
var max = 0;
jQuery.map(arr, function (obj) {
if (obj.attr > max)
max = obj.attr;
});
答案 13 :(得分:1)
又快又脏:
Object.defineProperty(Array.prototype, 'min',
{
value: function(f)
{
f = f || (v => v);
return this.reduce((a, b) => (f(a) < f(b)) ? a : b);
}
});
Object.defineProperty(Array.prototype, 'max',
{
value: function(f)
{
f = f || (v => v);
return this.reduce((a, b) => (f(a) > f(b)) ? a : b);
}
});
console.log([1,2,3].max());
console.log([1,2,3].max(x => x*(4-x)));
console.log([1,2,3].min());
console.log([1,2,3].min(x => x*(4-x)));
答案 14 :(得分:0)
Here is very simple way to go:
Your DataSet.
let numberArray = [
{
"x": "8/11/2009",
"y": 0.026572007
},
{
"x": "8/12/2009",
"y": 0.025057454
},
{
"x": "8/13/2009",
"y": 0.024530916
},
{
"x": "8/14/2009",
"y": 0.031004457
}
]
1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) >> [0.026572007,0.025057454,0.024530916,0.031004457]
2. let maxValue = Math.max.apply(null, result)
console.log(maxvalue) >> 0.031004457
答案 15 :(得分:0)
很简单
const array1 = [
{id: 1, val: 60},
{id: 2, val: 2},
{id: 3, val: 89},
{id: 4, val: 78}
];
const array2 = [1,6,8,79,45,21,65,85,32,654];
const max = array1.reduce((acc, item) => acc = acc > item.val ? acc : item.val, 0);
const max2 = array2.reduce((acc, item) => acc = acc > item ? acc : item, 0);
console.log(max);
console.log(max2);