Javascript 在对象的属性中获取最小值/最大值的快速方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11142884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fast way to get the min/max values among properties of object
提问by Youssef
I have an object in javascript like this:
我在 javascript 中有一个像这样的对象:
{ "a":4, "b":0.5 , "c":0.35, "d":5 }
Is there a fast way to get the minimum and maximum value among the properties without having to loop through them all? because the object I have is huge and I need to get the min/max value every two seconds. (The values of the object keeps changing).
有没有一种快速的方法来获得属性中的最小值和最大值而不必遍历它们?因为我拥有的对象很大,我需要每两秒获取一次最小值/最大值。(对象的值不断变化)。
采纳答案by carlosfigueira
There's no way to find the maximum / minimum in the general case without looping through all the nelements (if you go from, 1 to n-1, how do you know whether the element nisn't larger (or smaller) than the current max/min)?
在不循环遍历所有n 个元素的情况下,没有办法在一般情况下找到最大值/最小值(如果你从 1 到 n-1,你怎么知道元素n是否不大于(或小于)当前最大/最小)?
You mentioned that the values change every couple of seconds. If you know exactly which values change, you can start with your previous max/min values, and only compare with the new ones, but even in this case, if one of the values which were modified was your old max/min, you may need to loop through them again.
您提到值每隔几秒钟就会更改一次。如果您确切知道哪些值发生了变化,则可以从以前的最大值/最小值开始,并仅与新值进行比较,但即使在这种情况下,如果修改的值之一是旧的最大值/最小值,您也可以需要再次遍历它们。
Another alternative - again, only if the number of values which change are small - would be to store the values in a structure such as a tree or a heap, and as the new values arrive you'd insert (or update) them appropriately. But whether you can do that is not clear based on your question.
另一种选择——同样,只有当改变的值的数量很小时——将值存储在树或堆等结构中,当新值到达时,您将适当地插入(或更新)它们。但是根据您的问题,您是否可以做到这一点尚不清楚。
回答by ?ime Vidas
Try this:
尝试这个:
var arr = Object.keys( obj ).map(function ( key ) { return obj[key]; });
and then:
进而:
var min = Math.min.apply( null, arr );
var max = Math.max.apply( null, arr );
Live demo:http://jsfiddle.net/7GCu7/1/
现场演示:http : //jsfiddle.net/7GCu7/1/
Update:Modern version (ES6+)
更新:现代版本(ES6+)
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
let arr = Object.values(obj);
let min = Math.min(...arr);
let max = Math.max(...arr);
console.log( `Min value: ${min}, max value: ${max}` );
回答by Niet the Dark Absol
min
and max
have to loop through the input array anyway - how else would they find the biggest or smallest element?
min
并且max
无论如何都必须遍历输入数组-否则他们将如何找到最大或最小的元素?
So just a quick for..in
loop will work just fine.
所以只需一个快速for..in
循环就可以了。
var min = Infinity, max = -Infinity, x;
for( x in input) {
if( input[x] < min) min = input[x];
if( input[x] > max) max = input[x];
}
回答by Dave Kalu
You could try:
你可以试试:
const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5
回答by Andrey Kudriavtsev
// 1. iterate through object values and get them
// 2. sort that array of values ascending or descending and take first,
// which is min or max accordingly
let obj = { 'a': 4, 'b': 0.5, 'c': 0.35, 'd': 5 }
let min = Object.values(obj).sort((prev, next) => prev - next)[0] // 0.35
let max = Object.values(obj).sort((prev, next) => next - prev)[0] // 5
回答by Neel Rathod
You can also try with Object.values
你也可以试试 Object.values
const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };
const vals = Object.values(points);
const max = Math.max(...vals);
const min = Math.min(...vals);
console.log(max);
console.log(min);
回答by Sergey Zhigalov
Using the lodash libraryyou can write shorter
使用lodash 库,你可以写得更短
_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();
回答by JBallin
Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.
这是一个解决方案,它允许您也返回密钥并且只执行一个循环。它对对象的条目进行排序(按 val),然后返回第一个和最后一个。
Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.
此外,它返回可以替换现有对象的排序对象,以便将来的排序更快,因为它已经是半排序的 = 优于 O(n)。重要的是要注意对象在 ES6 中保持它们的顺序。
const maxMinVal = (obj) => {
const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);
return {
min: sortedEntriesByVal[0],
max: sortedEntriesByVal[sortedEntriesByVal.length - 1],
sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),
};
};
const obj = {
a: 4, b: 0.5, c: 0.35, d: 5
};
console.log(maxMinVal(obj));
回答by user4815162342
For nested structures of different depth, i.e. {node: {leaf: 4}, leaf: 1}
, this will work (using lodash or underscore):
对于不同深度的嵌套结构,即{node: {leaf: 4}, leaf: 1}
,这将起作用(使用 lodash 或下划线):
function getMaxValue(d){
if(typeof d === "number") {
return d;
} else if(typeof d === "object") {
return _.max(_.map(_.keys(d), function(key) {
return getMaxValue(d[key]);
}));
} else {
return false;
}
}
回答by user12723650
var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))