计算javascript对象中的出现次数

时间:2015-02-07 23:22:30

标签: javascript arrays loops

Object {green: 3, red: 2, blue: 1, yellow: 1, mint: 3}

我想遍历此对象并返回数组中出现次数最多的键(按值)。在这种情况下,它将是薄荷和绿色,如["mint", "green"]

到目前为止,我得到了这个

for (var i = 0; i < key(obj).length; i++) {
  ... // no idea
}

任何帮助或方向表示赞赏。谢谢!

5 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var obj = {"green": 3, "red": 2, "blue": 1, "yellow": 1, "mint": 3},
    keys = Object.keys(obj),    // get all keys as array
    max = Math.max.apply(Math, keys.map(function(key) { return obj[key]; })),    // find the biggest number of occurrences
    result;
	
result = keys.filter(function(key) {    // find the relevant keys
	return obj[key] == max;
});

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你需要这个:

var maxValue = -10000000;
for(var prop in obj) {
 if(!obj.hasOwnProperty(prop)) {
  continue;
 }
 if(obj[prop] > maxValue) {
  maxValue = obj[prop];
 }
}
// show maxValue

注意:您需要obj.hasOwnProperty(prop),因为js中的对象具有一些您在循环中不需要的特殊属性。

答案 2 :(得分:0)

var data = {green: 3, red: 2, blue: 1, yellow: 1, mint: 3}
var maxProperty = null, maxValue = -1;
for (var prop in data) {
  if (data.hasOwnProperty(prop)) {
    var value = data[prop]
    if (value > maxValue) {
      maxProperty = prop
      maxValue = value
    }
  }
}

答案 3 :(得分:0)

您可以执行以下操作:

&#13;
&#13;
var someObjects = {
  green: 3,
  red: 2,
  blue: 1,
  yellow: 1,
  mint: 3
};


function findOccurances(of, inn) {
  var array = [];
  for (var obj in inn) {
    if (someObject[obj] == of) {
      array.push(obj);
    }
  }
  return array;
}
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

编辑: 我认为一个更安心的解决方案是有序的。这是一个:

var bar = { green: 3, red: 2, blue: 1, yellow: 1, mint: 3 };

var findMaxProperties = function (foo) {
  var keys = Object.keys(foo);
  var max = keys.map(function (key) {
    return foo[key];
  }).reduce(function (previous, current) {
    return Math.max(previous, current);
  });
  return keys.filter(function (key) {
    return foo[key] == max;
  });
};

var result = findMaxProperties(bar);
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="result"></div>

如果我正确理解你的问题(如果是这种情况那么你真的需要编辑它:))那么你想要查看一个对象并找到具有最高数值的属性。如果是这种情况,那么沿着这些方向的东西就可以解决问题。

var foo = { green: 3, red: 2, blue: 1, yellow: 1, mint: 3 };

var maxValue = Number.MIN_VALUE, maxValueProperties = [];
for (var key in foo) {
  if(foo[key] == maxValue) {
    maxValueProperties.push(key);
  }
  if(foo[key] > maxValue) {
    maxValue = foo[key];
    maxValueProperties = [];
    maxValueProperties.push(key);
  }  
}

$('#result').text(maxValueProperties);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="result">result</div>