获取具有相同(最高)出现的数组的所有元素

时间:2015-12-29 11:24:21

标签: javascript arrays

我有一个像[1,4,3,1,6,5,1,4,4]

这样的数组

此处最高元素频率为3,我需要从上面示例中选择具有3个频率的所有元素,如[1,4]

我试过这个

var count = {},array=[1,4,3,1,6,5,1,4,4],
    value;
 for (var i = 0; i < array.length; i++) {
            value = array[i];
            if (value in count) {
                count[value]++;
            } else {
                count[value] = 1;
            }
        }
console.log(count);

这将以其频率输出数组元素,现在我需要所有频率最高的元素。

6 个答案:

答案 0 :(得分:2)

我按照以下方式处理此问题。

首先,写下您认为问题如何解决 IN ENGLISH ,或接近英语(或当然是您的母语!)的问题。记下每一步。从高级版本开始,例如:

  1. 计算输入中每​​个元素的频率。

  2. 找到最高频率。

  3. 等等。此时,您不要陷入实施细节中,这一点非常重要。您的解决方案几乎适用于任何编程语言。

    接下来通过添加子步骤来充实每一步。例如,您可以写:

    1. 找到最高频率。

      一个。假设最高频率为零。

      湾检查每个频率。如果它高于当前最高频率,则将其设置为当前最高频率。

    2. 通过手动执行算法来测试算法。

      接下来,将您撰写的内容转换为有时称为 pseudo-code 的内容。正是在这一点上,我们的算法开始看起来有点像计算机程序,但仍然很容易被人类阅读。我们现在可以使用变量来表示事物。例如,我们可以写&#34; max_freq←cur_freq&#34;。我们可以引用数组,并编写循环。

      最后,将您的伪代码转换为JS。如果一切顺利,它应该第一次工作!

      近年来,很多人都在使用JavaScript,没有任何接触过如何思考算法,甚至是简单算法。他们想象他们需要以某种方式能够或者神奇地达到他们能够达到的程度,凭空捏造JS,就像说方言的人一样。事实上,最好的程序员在面对问题时不会立即开始编写array.reduce;他们总是经历这个过程 - 即使只是在他们的脑海中 - 思考关于解决问题的方法,这是一个非常值得学习的方法。 / p>

      如果你没有掌握这项技能,那么每当你无法解决问题时,你就会把余下的职业生涯发布到SO上。

答案 1 :(得分:1)

Array.prototype.reduce()提案用于获取临时对象countObject.keys()用于获取临时对象的键,Array.prototype.sort()方法用于排序计数结果和{{ 3}}仅获取计数最多的最高值。

编辑:Kudos @ Xotic750,现在返回原始值。

var array = [1, 4, 3, 1, 6, 5, 1, 4, 4],
    result = function () {
        var temp = array.reduce(function (r, a, i) {
            r[a] = r[a] || { count: 0, value: a };
            r[a].count++;
            return r;
        }, {});
        return Object.keys(temp).sort(function (a, b) {
            return temp[b].count - temp[a].count;
        }).filter(function (a, _, aa) {
            return temp[aa[0]].count === temp[a].count;
        }).map(function (a) {
            return temp[a].value;
        });
    }();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

以不同的尝试获得奖金

var array = [1, 4, 3, 1, 6, 5, 1, 4, 4],
    result = array.reduce(function (r, a) {
        r.some(function (b, i) {
            var p = b.indexOf(a);
            if (~p) {
                b.splice(p, 1);
                r[i + 1] = r[i + 1] || [];
                r[i + 1].push(a);
                return true;
            }
        }) || (
            r[1] = r[1] || [],
            r[1].push(a)
        );
        return r;
    }, []).pop();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 2 :(得分:0)

你可以试试这个

var input = [1,4,3,1,6,5,1,4,4];

var output = {};

for ( var counter = 0; counter < input.length; counter++ )
{
   if ( !output[ input[ counter ] ] )
   {
      output[ input[ counter ] ] = 0;
   }
   output[ input[ counter ] ]++;
}

var outputArr = [];
for (var key in output)
{
  outputArr.push([key, output[key]])
}
outputArr = outputArr.sort(function(a, b) {return b[1] - a[1]})

现在outputArr的初始值是频率最高的值

以下是fiddle

检查此更新的fiddle(这将提供您想要的输出)

var input = [1,4,3,1,6,5,1,4,4];

var output = {}; // this object holds the frequency of each value

for ( var counter = 0; counter < input.length; counter++ )
{
   if ( !output[ input[ counter ] ] )
   {
      output[ input[ counter ] ] = 0; //initialized to 0 if value doesn't exists
   }
   output[ input[ counter ] ]++; //increment the value with each occurence
}
var outputArr = [];
var maxValue = 0;
for (var key in output)
{
  if (  output[key] > maxValue )
  {
    maxValue = output[key]; //find out the max value 
  }
  outputArr.push([key, output[key]])
}
var finalArr = []; //this array holds only those keys whose value is same as the highest value
for ( var counter = 0; counter < outputArr.length; counter++ )
{
  if ( outputArr[ counter ][ 1 ]  == maxValue )
  {
     finalArr.push( outputArr[ counter ][ 0 ] )
  }
}

console.log( finalArr );

答案 3 :(得分:0)

我会做这样的事情。它没有经过测试,但它的评论是为了帮助您了解我的方法。

// Declare your array
var initial_array = [1,4,3,1,6,5,1,4,4];

// Declare an auxiliar counter
var counter = {};

// Loop over the array
initial_array.forEach(function(item){

    // If the elements is already in counter, we increment the repetition counter.
    if counter.hasOwnProperty(item){
        counter[item] += 1;

    // If the element is not in counter, we set the repetitions to one
    }else{
        counter[item] = 1;
    }
});

// counter = {1 : 3, 4 : 3, 3 : 1, 6 : 1, 5 : 1}

// We move the object keys to an array (sorting it's more easy this way)
var sortable = [];

for (var element in counter)

    sortable.push([element, counter[element]]);

// sortable = [ [1,3], [4,3], [3,1], [6,1], [5,1] ]

// Sort the list
sortable.sort(function(a, b) {return a[1] - b[1]})

// sortable = [ [1,3], [4,3], [3,1], [6,1], [5,1] ] sorted, in this case both are equals

// The elements in the firsts positions are the elements that you are looking for

// This auxiliar variable will help you to decide the biggest frequency (not the elements with it)
higgest = 0;

// Here you will append the results
results = [];

// You loop over the sorted list starting for the elements with more frequency
sortable.forEach(function(item){

    // this condition works because we have sorted the list previously. 
    if(item[1] >= higgest){

        higgest = item[1];
        results.push(item[0]);

    }

});

答案 4 :(得分:0)

我非常关注@torazaburo所说的话。

我也成为ES6的粉丝,因为它越来越多地进入我的日常浏览器。所以,这是一个使用ES6的解决方案,现在在我的浏览器中工作。

加载'use strict'; // Your array of values. const array = [1, 4, 3, 1, 6, 5, 1, 4, 4]; // An ES6 Map, for counting the frequencies of your values. // Capable of distinguishing all unique values except `+0` and `-0` // i.e. SameValueZero (see ES6 specification for explanation) const frequencies = new Map(); // Loop through all the `values` of `array` for (let item of array) { // If item exists in frequencies increment the count or set the count to `1` frequencies.set(item, frequencies.has(item) ? frequencies.get(item) + 1 : 1); } // Array to group the frequencies into list of `values` const groups = []; // Loop through the frequencies for (let item of frequencies) { // The `key` of the `entries` iterator is the value const value = item[0]; // The `value` of the `entries` iterator is the frequency const frequency = item[1]; // If the group exists then append the `value`, // otherwise add a new group containing `value` if (groups[frequency]) { groups[frequency].push(value); } else { groups[frequency] = [value]; } } // The most frequent values are the last item of `groups` const mostFrequent = groups.pop(); document.getElementById('out').textContent = JSON.stringify(mostFrequent); console.log(mostFrequent);以修复浏览器浏览器错误和缺陷,建议在所有环境中使用。

<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.0/es6-shim.js"></script>
<pre id="out"></pre>
Date.today + eval('1.month')

答案 5 :(得分:-1)

你可以这样做来查找每个数字的计数

&#13;
&#13;
var array = [1, 4, 3, 1, 6, 5, 1, 4, 4];

var frequency = array.reduce(function(sum, num) {
  if (sum[num]) {
    sum[num] = sum[num] + 1;
  } else {
    sum[num] = 1;
  }
  return sum;
}, {});

console.log(frequency)
&#13;
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
&#13;
&#13;
&#13;