如何在javascript中计算数组中的重复值

时间:2013-10-16 04:28:17

标签: javascript arrays

目前,我有一个这样的数组:

var uniqueCount = Array();

经过几个步骤,我的数组看起来像这样:

uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];

如何计算阵列中有多少a,b,c?我希望得到一个结果:

a = 3
b = 1
c = 2
d = 2

31 个答案:

答案 0 :(得分:222)

var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });

答案 1 :(得分:45)

这样的事情:

    uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
    var  count = {};
    uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
    console.log(count);

如果您不希望在旧版浏览器中使用它,请使用简单的for循环而不是forEach。

答案 2 :(得分:25)

我偶然发现了这个(非常古老的)问题。有趣的是,最明显和最优雅的解决方案(imho)缺失:Array.prototype.reduce(...)。自2011年左右(IE)或更早(所有其他)以来,所有主流浏览器都支持此功能:



var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
  prev[cur] = (prev[cur] || 0) + 1;
  return prev;
}, {});

// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}




答案 3 :(得分:15)

function count() {
    array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

    array_elements.sort();

    var current = null;
    var cnt = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != current) {
            if (cnt > 0) {
                document.write(current + ' comes --> ' + cnt + ' times<br>');
            }
            current = array_elements[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        document.write(current + ' comes --> ' + cnt + ' times');
    }

}

Demo Fiddle

答案 4 :(得分:8)

基于减少数组函数的单行

const uniqueCount =  ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));

答案 5 :(得分:6)

没有人对此似乎使用内置的Map(),这往往是我与Array.prototype.reduce()结合使用的目的:

const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());
console.log(...result);

注意,如果要在较旧的浏览器中使用它,则必须polyfill Map()

答案 6 :(得分:4)

我认为这是如何计算数组中具有相同值的事件的最简单方法。

var a = [true, false, false, false];
a.filter(function(value){
    return value === false;
}).length                                      

答案 7 :(得分:4)

你可以在不使用任何for / while循环的情况下解决它。

function myCounter(inputWords) {        
    return inputWords.reduce( (countWords, word) => {
        countWords[word] = ++countWords[word] || 1;
        return countWords;
    }, {});
}

希望它可以帮到你!

答案 8 :(得分:3)

您可以拥有一个包含计数的对象。遍历列表并增加每个元素的计数:

var counts = {};

uniqueCount.forEach(function(element) {
  counts[element] = (counts[element] || 0) + 1;
});

for (var element in counts) {
  console.log(element + ' = ' + counts[element]);
} 

答案 9 :(得分:3)

你可以这样做:

uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();

for(var i = 0; i < uniqueCount.length; i++) {
 if(map[uniqueCount[i]] != null) {
    map[uniqueCount[i]] += 1;
} else {
    map[uniqueCount[i]] = 1;
    }
}

现在你有一张包含所有字符数的地图

答案 10 :(得分:2)

const obj = {};
const uniqueCount = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a' ];
for (let i of uniqueCount) obj[i] ? obj[i]++ : (obj[i] = 1);
console.log(obj);

答案 11 :(得分:2)

简单更好,一个变量,一个函数:)

const counts = arr.reduce((acc, value) => ({
   ...acc,
   [value]: (acc[value] || 0) + 1
}), {});

答案 12 :(得分:1)

包含字母的数组中的重复:

&#13;
&#13;
var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
  sortedArr = [],
  count = 1;

sortedArr = arr.sort();

for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}
&#13;
&#13;
&#13;

包含数字的数组中的重复:

&#13;
&#13;
var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
  sortedArr = [],
  count = 1;
sortedArr = arr.sort(function(a, b) {
  return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}
&#13;
&#13;
&#13;

答案 13 :(得分:1)

uniqueCount = ["a","b","a","c","b","a","d","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach((i) => { count[i] = ++count[i]|| 1});
console.log(count);

答案 14 :(得分:1)

import pickle, zlib 

def store_obj(file_, obj):
    compressed = zlib.compress(pickle.dumps(obj, protocol=-1), level=9)
    file_.write(len(compressed).to_bytes(4, "little"))
    file_.write(compressed)

def get_obj(file_):

     obj_size = int.from_bytes(file_.read(4), "little")
     if obj_size == 0:
         return None
     data = zlib.decompress(self.file_.read(obj_size))
     return pickle.loads(data)

答案 15 :(得分:0)

好的答案组合:

var count = {};
var arr = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
var iterator = function (element) {
    count[element] = (count[element] || 0) + 1;
}

if (arr.forEach) {
    arr.forEach(function (element) {
        iterator(element);
    });
} else {
    for (var i = 0; i < arr.length; i++) {
        iterator(arr[i]);
    }
}  

希望它有用。

答案 16 :(得分:0)

通过使用array.map,我们可以减少循环,请参阅jsfiddle

eruptions = [3.6, 1.8, 3.333, 2.283, 4.533, 2.883, 4.7, 3.6, 1.95, 4.35, 1.833, 3.917, 4.2, 1.75, 4.7, 2.167, 1.75, 4.8, 1.6, 4.25, 1.8, 1.75, 3.45, 3.067, 4.533, 3.6, 1.967, 4.083, 3.85, 4.433, 4.3, 4.467, 3.367, 4.033, 3.833, 2.017, 1.867, 4.833, 1.833, 4.783, 4.35, 1.883, 4.567, 1.75, 4.533, 3.317, 3.833, 2.1, 4.633, 2.0, 4.8, 4.716, 1.833, 4.833, 1.733, 4.883, 3.717, 1.667, 4.567, 4.317, 2.233, 4.5, 1.75, 4.8, 1.817, 4.4, 4.167, 4.7, 2.067, 4.7, 4.033, 1.967, 4.5, 4.0, 1.983, 5.067, 2.017, 4.567, 3.883, 3.6, 4.133, 4.333, 4.1, 2.633, 4.067, 4.933, 3.95, 4.517, 2.167, 4.0, 2.2, 4.333, 1.867, 4.817, 1.833, 4.3, 4.667, 3.75, 1.867, 4.9, 2.483, 4.367, 2.1, 4.5, 4.05, 1.867, 4.7, 1.783, 4.85, 3.683, 4.733, 2.3, 4.9, 4.417, 1.7, 4.633, 2.317, 4.6, 1.817, 4.417, 2.617, 4.067, 4.25, 1.967, 4.6, 3.767, 1.917, 4.5, 2.267, 4.65, 1.867, 4.167, 2.8, 4.333, 1.833, 4.383, 1.883, 4.933, 2.033, 3.733, 4.233, 2.233, 4.533, 4.817, 4.333, 1.983, 4.633, 2.017, 5.1, 1.8, 5.033, 4.0, 2.4, 4.6, 3.567, 4.0, 4.5, 4.083, 1.8, 3.967, 2.2, 4.15, 2.0, 3.833, 3.5, 4.583, 2.367, 5.0, 1.933, 4.617, 1.917, 2.083, 4.583, 3.333, 4.167, 4.333, 4.5, 2.417, 4.0, 4.167, 1.883, 4.583, 4.25, 3.767, 2.033, 4.433, 4.083, 1.833, 4.417, 2.183, 4.8, 1.833, 4.8, 4.1, 3.966, 4.233, 3.5, 4.366, 2.25, 4.667, 2.1, 4.35, 4.133, 1.867, 4.6, 1.783, 4.367, 3.85, 1.933, 4.5, 2.383, 4.7, 1.867, 3.833, 3.417, 4.233, 2.4, 4.8, 2.0, 4.15, 1.867, 4.267, 1.75, 4.483, 4.0, 4.117, 4.083, 4.267, 3.917, 4.55, 4.083, 2.417, 4.183, 2.217, 4.45, 1.883, 1.85, 4.283, 3.95, 2.333, 4.15, 2.35, 4.933, 2.9, 4.583, 3.833, 2.083, 4.367, 2.133, 4.35, 2.2, 4.45, 3.567, 4.5, 4.15, 3.817, 3.917, 4.45, 2.0, 4.283, 4.767, 4.533, 1.85, 4.25, 1.983, 2.25, 4.75, 4.117, 2.15, 4.417, 1.817, 4.467]
waiting = [79, 54, 74, 62, 85, 55, 88, 85, 51, 85, 54, 84, 78, 47, 83, 52, 62, 84, 52, 79, 51, 47, 78, 69, 74, 83, 55, 76, 78, 79, 73, 77, 66, 80, 74, 52, 48, 80, 59, 90, 80, 58, 84, 58, 73, 83, 64, 53, 82, 59, 75, 90, 54, 80, 54, 83, 71, 64, 77, 81, 59, 84, 48, 82, 60, 92, 78, 78, 65, 73, 82, 56, 79, 71, 62, 76, 60, 78, 76, 83, 75, 82, 70, 65, 73, 88, 76, 80, 48, 86, 60, 90, 50, 78, 63, 72, 84, 75, 51, 82, 62, 88, 49, 83, 81, 47, 84, 52, 86, 81, 75, 59, 89, 79, 59, 81, 50, 85, 59, 87, 53, 69, 77, 56, 88, 81, 45, 82, 55, 90, 45, 83, 56, 89, 46, 82, 51, 86, 53, 79, 81, 60, 82, 77, 76, 59, 80, 49, 96, 53, 77, 77, 65, 81, 71, 70, 81, 93, 53, 89, 45, 86, 58, 78, 66, 76, 63, 88, 52, 93, 49, 57, 77, 68, 81, 81, 73, 50, 85, 74, 55, 77, 83, 83, 51, 78, 84, 46, 83, 55, 81, 57, 76, 84, 77, 81, 87, 77, 51, 78, 60, 82, 91, 53, 78, 46, 77, 84, 49, 83, 71, 80, 49, 75, 64, 76, 53, 94, 55, 76, 50, 82, 54, 75, 78, 79, 78, 78, 70, 79, 70, 54, 86, 50, 90, 54, 54, 77, 79, 64, 75, 47, 86, 63, 85, 82, 57, 82, 67, 74, 54, 83, 73, 73, 88, 80, 71, 83, 56, 79, 78, 84, 58, 83, 43, 60, 75, 81, 46, 90, 46, 74]
df = pd.DataFrame({'eruptions': eruptions, 'waiting': waiting})

s = sorted([str(round(i * 10, 1)) for i in df['eruptions']])
s = (
    pd.Series(s)
    .groupby([str(int(float(i) // 2 * 2)) for i in s])
    .apply(lambda group: "".join((x[-1] for x in group)))
    .reset_index()
)
print("\n".join(s['index'] +' | ' + s[0]))
# Output
# 16 | 070355555588
# 18 | 000022233333335577777777888822335777888
# 20 | 00002223378800035778
# 22 | 0002335578023578
# 24 | 00228
# 26 | 23
# 28 | 080
# 30 | 7
# 32 | 2337
# 34 | 250077
# 36 | 0000823577
# 38 | 2333335582225577
# 40 | 0000003357788888002233555577778
# 42 | 03335555778800233333555577778
# 44 | 02222335557780000000023333357778888
# 46 | 0000233357700000023578
# 48 | 00000022335800333
# 50 | 0370

测试:

function Check(){
    var arr = Array.prototype.slice.call(arguments);
    var result = [];
    for(i=0; i< arr.length; i++){
        var duplicate = 0;
        var val = arr[i];
        arr.map(function(x){
            if(val === x) duplicate++;
        })
        result.push(duplicate>= 2);
    }
    return result;
}

答案 17 :(得分:0)

示例如何返回字符串中最常用的字符。

function maxChar(str) {
    const charMap = {};

    let maxCharacter = '';
    let maxNumber = 0;

    for (let item of str) {
        charMap[item] = charMap[item] + 1 || 1;
    }

    for (let char in charMap) {
        if (charMap[char] > maxNumber) {
            maxNumber = charMap[char];
            maxCharacter = char;
        }
    }

    return maxCharacter;
}


console.log(maxChar('abcccccccd'))

答案 18 :(得分:0)

计算字符串中提供的字母

function countTheElements(){
    
    var str = "ssdefrcgfrdesxfdrgs";
    var arr = [];
    var count = 0;
    
    for(var i=0;i<str.length;i++){
        arr.push(str[i]);
        
    }
        arr.sort();
    for(var i=0;i<arr.length;i++){     
        if(arr[i] == arr[i-1]){
            count++;
        }else{        
            count = 1;        
        }
            if(arr[i] != arr[i+1]){
                console.log(arr[i] +": "+(count));
            }    
            
       }
    }
        countTheElements()

答案 19 :(得分:0)

let arr=[1,2,3,3,4,5,5,6,7,7]
let obj={}
for(var i=0;i<arr.length;i++){
    obj[arr[i]]=obj[arr[i]]!=null ?obj[arr[i]]+1:1 //stores duplicate in an obj

}
console.log(obj)
//returns object {1:1,:1,3:2,.....}

答案 20 :(得分:0)

用法:

wrap.common.getUniqueDataCount(, columnName);

代码:

function getUniqueDataCount(objArr, propName) {
        var data = [];
        objArr.forEach(function (d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });

        var uniqueList = [...new Set(data)];

        var dataSet = {};
        for (var i=0; i < uniqueList.length; i++) {
            dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
        }
        
        return dataSet;
    }

代码段

var data= [
          {a:'you',b:'b',c:'c',d:'c'},
          {a: 'you', b: 'b', c: 'c', d:'c'},
          {a: 'them', b: 'b', c: 'c', d:'c'},
          {a: 'them', b: 'b', c: 'c', d:'c'},
          {a: 'okay', b: 'b', c: 'c', d:'c'},
          {a: 'okay', b: 'b', c: 'c', d:'c'},
          ];
          
  console.log(getUniqueDataCount(data, 'a'));       
  
  function getUniqueDataCount(objArr, propName) {
        var data = [];
        objArr.forEach(function (d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });

        var uniqueList = [...new Set(data)];

        var dataSet = {};
        for (var i=0; i < uniqueList.length; i++) {
            dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
        }

        return dataSet;
    }

答案 21 :(得分:0)


// Initial array
let array  = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];

// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];

// This array counts duplicates [['a', 3], ['b', 2], ..., ['h', 3]] 
let duplicates  = unique.map(value => [value, array.filter(str => str === value).length]);

答案 22 :(得分:0)

public class CalculateCount {
public static void main(String[] args) {
    int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
    Arrays.sort(a);
    int count=1;
    int i;
    for(i=0;i<a.length-1;i++){
        if(a[i]!=a[i+1]){
            System.out.println("The Number "+a[i]+" appears "+count+" times");
            count=1;                
        }
        else{
            count++;
        }
    }
    System.out.println("The Number "+a[i]+" appears "+count+" times");

}   

}

答案 23 :(得分:0)

声明一个对象arr来保存唯一的键集。通过使用map遍历数组来填充arr。如果先前未找到密钥,则添加密钥并分配零值。在每次迭代中,增加密钥的值。

给出testArray:

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

解决方案:

var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});

JSON.stringify(arr)将输出

{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}

Object.keys(arr)将返回["a","b","c","d","e","f","g","h"]

查找任何项目的出现,例如b arr['b']将输出2

答案 24 :(得分:0)

var testArray = ['a','b','c','d','d','e','a','b','c','f','g' ,'h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);

答案 25 :(得分:0)

var arr = ['a','d','r','a','a','f','d'];  

//call function and pass your array, function will return an object with array values as keys and their count as the key values.
duplicatesArr(arr);

function duplicatesArr(arr){
    var obj = {}
    for(var i = 0; i < arr.length; i++){
        obj[arr[i]] = [];
        for(var x = 0; x < arr.length; x++){
            (arr[i] == arr[x]) ? obj[arr[i]].push(x) : '';
        }
        obj[arr[i]] = obj[arr[i]].length;
    }

    console.log(obj);
    return obj;
}

答案 26 :(得分:0)

最快的方法:

Сomputational complexity是O(n)。

function howMuchIsRepeated_es5(arr) {
	const count = {};
	for (let i = 0; i < arr.length; i++) {
		const val = arr[i];
		if (val in count) {
			count[val] = count[val] + 1;
		} else {
			count[val] = 1;
		}
	}

	for (let key in count) {
		console.log("Value " + key + " is repeated " + count[key] + " times");
	}
}

howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

最短的代码:

使用ES6。

function howMuchIsRepeated_es6(arr) {
	// count is [ [valX, count], [valY, count], [valZ, count]... ];
	const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);

	for (let i = 0; i < count.length; i++) {
		console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
	}
}

howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

答案 27 :(得分:0)

  
    // new example.
    var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];
    
    function findOdd(para) {
      var count = {};
      para.forEach(function(para) {
      count[para] = (count[para] || 0) + 1;
      });
      return count;
    }
    
    console.log(findOdd(str));
    
    

答案 28 :(得分:0)

例如创建一个文件demo.js,并在节点为demo.js的控制台中运行该文件,您将发现矩阵形式的元素。

var multipleDuplicateArr = Array(10).fill(0).map(()=>{return Math.floor(Math.random() * Math.floor(9))});
console.log(multipleDuplicateArr);

var resultArr = Array(Array('KEYS','OCCURRENCE'));

for (var i = 0; i < multipleDuplicateArr.length; i++) {
  var flag = true;
  for (var j = 0; j < resultArr.length; j++) {
     if(resultArr[j][0] == multipleDuplicateArr[i]){
       resultArr[j][1] = resultArr[j][1] + 1;
       flag = false;
      }
  }
  if(flag){
    resultArr.push(Array(multipleDuplicateArr[i],1));
  }
}

console.log(resultArr);

您将在控制台中获得如下结果:

[ 1, 4, 5, 2, 6, 8, 7, 5, 0, 5 ] . // multipleDuplicateArr
[ [ 'KEYS', 'OCCURENCE' ],        // resultArr
  [ 1, 1 ],
  [ 4, 1 ],
  [ 5, 3 ],
  [ 2, 1 ],
  [ 6, 1 ],
  [ 8, 1 ],
  [ 7, 1 ],
  [ 0, 1 ] ]

答案 29 :(得分:0)

var string = ['a','a','b','c','c','c','c','c','a','a','a'];

function stringCompress(string){

var obj = {},str = "";
string.forEach(function(i) { 
  obj[i] = (obj[i]||0) + 1;
});

for(var key in obj){
  str += (key+obj[key]);
}
  console.log(obj);
  console.log(str);
}stringCompress(string)

/*
Always open to improvement ,please share 
*/

答案 30 :(得分:-1)

在JavaScript中使用数组化简方法很简单:

    var arr = ['a','d','r','a','a','f','d'];
    console.log(arr.reduce((json,val)=>({...json,[val]:(json[val]|0)+1}),{}))
    //{ a:3,d:2,r:1,f:1 }