js计算重复出现次数

// input: [{a:2},1,”1”,1,{a:2}]
// desired output:  {“{a:2}”:2,”1”:3,}

var data = [{a:2},1,"1",1,{a:2}]
function getNewData(data) {
    if(!data.length) return {}
    let obj = {}
    for (let i = 0; i < data.length; i++) {
        let key = data[i];
        if (typeof key === "object") {
            key = JSON.stringify(key)
        }
        if(obj[key]){
            obj[key]++
        }else{
            obj[key] = 1
        }
    }
    return obj
}
console.log(getNewData(data))

你可能感兴趣的:(js计算重复出现次数)