检查数组中是否有重复的值,获取值并获取计数 [英] Check an array for duplicate values, get value and get count

查看:57
本文介绍了检查数组中是否有重复的值,获取值并获取计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have pushed a random amount of strings into an array.

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

Id喜欢检索Arrays值并获得将它们推入Array的次数。
i.E

Id like to retrieve the Arrays values and get the amount of times they were pushed into the Array. i.E

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

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

我看不到如何使用循环比较数组[i]以及数组的所有其他值,尤其是考虑到的array.length是随机确定的吗?

I dont see how i can use a loop to compare array[i] with all the other values of the array, especially considerung array.length is randomly determined ?

谢谢

推荐答案

使用设置为数组值的键创建一个对象并开始计数!

Create an object with the keys set as the array values and start counting!

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

arrayMap 现在将拥有所有数组值的计数。

arrayMap will now have a count of all your array values.

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

这篇关于检查数组中是否有重复的值,获取值并获取计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆