检查数组是否有重复值,获取值并获得计数

时间:2014-10-07 13:20:04

标签: javascript arrays

我已将随机数量的字符串推入数组中。

var array = ["car", "plane", "plane", "car", "car"];

我想检索Arrays值并获取它们被推入Array的次数。 即

var a = "car";
var aCount = 3;
var b = "plane";
var bCount = 2;

var text = "'" + a + "'" + " was found " + aCount + " times";
return text

我看不出如何使用循环来比较array [i]和数组的所有其他值,尤其是Considerung array.length是随机确定的?

谢谢

4 个答案:

答案 0 :(得分:2)

创建一个对象,将键设置为数组值并开始计数!

var arrayMap = {};
for (var i = 0; i < array.length; i++) {
    if (arrayMap.hasOwnProperty(array[i])) {
        arrayMap[array[i]]++;
    } else {
        arrayMap[array[i]] = 1;
    }
}

arrayMap现在将计算所有数组值。

演示:http://jsfiddle.net/oe0x6dbg/

答案 1 :(得分:1)

你可以Array.reduce

var array = ["car", "plane", "plane", "car", "car"];

var result = array.reduce(function(dict, item) {
                 dict[item] = (dict[item] || 0) + 1;
                 return dict;
             }, {});

for(var prop in result) {
    console.log('\'' + prop + '\' was found ' + result[prop] + ' times');
}

/*
    result = {
        'car': 3,
        'plane': 2
    }

    Console:
    --------
    'car' was found 3 times
    'plane' was found 2 times
*/

答案 2 :(得分:0)

你可以这样做

var arrStr = array.join();
var result = {};
for (var i = 0; i < array.length; i++) {
    result[array[i]] = arrStr.match(new RegExp(array[i], "g")).length;
    arrStr.replace(new RegExp(array[i], "g"), "");
}
console.log(result); // {car: 3, plane: 2}

答案 3 :(得分:0)

一个简单的解决方案可能是添加一个&#34; count&#34;像这样的对象:

var array = ["car", "plane", "plane", "car", "car"];

var count = {};

// Map each element in the array to a key in the object
for (var i = 0; i < array.length; i++) {
    if (typeof count[array[i]] === 'undefined') {
        count[array[i]] = 1;
    } else {
        count[array[i]]++;
    }
}

// Loop through the object and print out the counts
for (var i in count) {
    console.log("'" + i + "'" + " was found " + count[i] + " times");
}

JSFiddle