javascript - JS : Get number of same values

标签 javascript algorithm

假设我有这个数组:

[1, 2, 2, 3, 3, 3, 4]

我如何返回包含值出现次数的数组/对象,例如:

{1:1, 2:2:, 3:3, 4:1}

这是我目前所拥有的:

// sort first
arr.sort();

for (var i = 0, l = arr.length, i < l, i++) {
    // what should go here ???? 
}

最佳答案

// Our results will be loaded into cont
var cont = {};

// For each number in our value array
for ( var i = 0; i < vals.length; i++ ) {
   // If it's found in the result array
   cont[ vals[i] ]
     // Increment it
     ? cont[ vals[i] ]++
     // Else, set it to 1
     : cont[ vals[i] ] = 1 ;
}

可以使用 while 循环和变量赋值变得更简单:

var vals = [1, 2, 2, 3, 3, 3, 4], // Values to cycle through
    cont = {},                    // Object to store results in
    indx = i = -1;                // Index and Counting variables

while ( indx = vals[ ++i ] )      // While a value exists for location i
  cont[ indx ]                    // Check to see if it's in the result object
    ? cont[ indx ]++              // If it is, increment it
    : cont[ indx ] = 1 ;          // If it is not, set it to 1

关于javascript - JS : Get number of same values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621988/

相关文章:

algorithm - 文件.TSP(旅行推销员)的含义

algorithm - 如何查找矩阵中唯一直线的数量

javascript - 在 Javascript 中计算斐波那契数列的最有效方法

c# - 如何解决素数函数的Big-O Notation?

javascript - Facebook OAuth 与 Firebase 和 Expo

javascript - 如何使用 javascript 提交 mvc 表单,同时传递 Controller 名称和操作方法

javascript - 为什么我无法在 Javascript Date 对象上使用 getDay() 方法和 getUTCDay() 方法获得相同的结果

javascript - 在 Angular JS 中删除下划线并添加财政年度

javascript - 将 "include"用于 HTML 代码时,边栏菜单不起作用

python - 根据分布生成一组随机整数列表