简体   繁体   English

从字典javascript获取所有最小值

[英]Getting all minimal Values from dictionary javascript

I have a long dictionary with many entries {y:10, au:41, w:41, m:11, u:21, t:1, d:1} What i need is to get all keys with the lowest value in a array. 我有一个很长的字典,有许多条目{y:10, au:41, w:41, m:11, u:21, t:1, d:1}我需要的是获得具有最低值的所有键一个数组。 I found this ( Getting key with the highest value from object ) but that doesn't work for multiple minimums(maximums) 我发现了这个( 从对象获取具有最高值的键 )但是这不适用于多个最小值(最大值)

and i need to use only core javascript. 我只需要使用核心JavaScript。

The fastest and easiest is probably to get the objects keys as an array with Object.keys , and filter that array based on items having the lowest value. 最快和最简单的可能是使用Object.keys将对象键作为数组获取,并根据具有最低值的项过滤该数组。
One would need to find the lowest value first, then filter, here's one way to do that 首先需要找到最低值,然后过滤,这是一种方法

 var obj = {y:10, au:41, w:41, m:11, u:21, t:1, d:1}; var keys = Object.keys(obj); var lowest = Math.min.apply(null, keys.map(function(x) { return obj[x]} )); var match = keys.filter(function(y) { return obj[y] === lowest }); document.body.innerHTML = '<pre>' +JSON.stringify(match, null, 4)+ '</pre>'; 

Getting the keys, then creating a array of the values that is passed to Math.min.apply to get the lowest value in the object. 获取键,然后创建传递给Math.min.apply的值数组,以获取对象中的最小值。

Then it's just a matter of filtering the keys for whatever matches the lowest value in the object. 然后,只需过滤键中任何与对象中最低值匹配的内容。

Here's another way using sort 这是使用sort的另一种方式

var obj   = {y:10, au:41, w:41, m:11, u:21, t:1, d:1};
var keys  = Object.keys(obj).sort(function(a,b) { return obj[a] - obj[b]; });
var match = keys.filter(function(x) { return obj[x] === obj[keys[0]]; });

This is a solution with Array#reduce() : 这是Array#reduce()的解决方案:

 var object = { y: 10, au: 41, w: 41, m: 11, u: 21, t: 1, d: 1 }, result = function (o) { var keys = Object.keys(o); return keys.reduce(function (r, k) { if (o[k] < o[r[0]]) { return [k]; } if (o[k] === o[r[0]]) { r.push(k); } return r; }, [keys.shift()]); }(object); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM