如何计算javascript数组中值的实例数并声明获胜者

时间:2016-12-07 22:18:25

标签: javascript angularjs

我正在Angular中构建一个类似Tinder的应用程序。当用户向右滑动时,我正在抓取有关该对象的信息。所有图像都可以是6个集合中的一个。

用户只能向右滑动4次。这意味着我有4个场景。我要做的是计算所有正确滑动的集合的实例数。我希望这是有道理的。

因此,例如,如果我最终得到这样的数组:

[a, b, a, d]

获胜者将是A.我不太确定如何计算所有这些并确定A为胜利者。

感谢任何和所有帮助!

3 个答案:

答案 0 :(得分:1)

const input = ['a', 'b', 'a', 'd'];

const findMostFrequentItem = arr => {
  let occurences = {};
  arr.forEach(x => occurences[x] = occurences[x] ? occurences[x] + 1 : 1);
  return Object.keys(occurences).reduce((a, b) => occurences[a] > occurences[b] ? a : b );
};

console.log(findMostFrequentItem(input));

答案 1 :(得分:1)

在ES6中,underscore提供了一些小帮助,您可以执行以下操作:

var swipes = ["a", "b", "a", "d"];

// Calculate and store the frequency of each swipe
var frequency = swipes.reduce(function(frequency, swipe){
   var sofar = frequency[swipe];
   if(!sofar){
     frequency[swipe] = 1;
   }
   else {
     frequency[swipe] = frequency[swipe] + 1;
   }

   return frequency;
}, {}); // {} - start out with an empty frequency object

var max = Math.max.apply(null, Object.values(frequency)); // most frequent

// find key for the most frequent value
// Using underscore...
// var winner = _.findKey(frequency, val => val === max); 

// Without underscore
var winner = Object.keys(frequency).find(element => frequency[element] == max);

答案 2 :(得分:0)

尝试这样的事情:

function countNum(array, num){
    var count = 0;
    for(var i = 0; i < array.length; ++i){
        if(array[i] == num)
            count++;
    }
    return count
}

然后:

var a, b, c, d;
//other stuff

min = [0, 0]
arr = [a, b, c, d]
for (index in arr){
    c = countNum(array, arr[index])
    if (c > min[0]) {
        min = [c, arr[index]]
    }
}

jsfiddle here