如何检查数组中的元素是否重复?

时间:2014-08-04 19:24:49

标签: javascript arrays

大家好,我是编码的新手,我想知道如何在不知道这些对象的情况下,如何判断数组是否有重复的对象而不管它们的顺序是什么?例如:

我创建一个空数组:

var random_array = [];

然后我使用一个函数来推送该数组中的对象,所以我最终得到:

var random_array = [ball, ball, tree, ball, tree, bus, car];

在上面的数组中,我们有:

3个球,2棵树,1辆公共汽车,1辆汽车。

那么我怎样才能知道这些重复的数字呢?我应该使用for循环还是什么?无论如何,我是编码的新手,所以请耐心等待。并提前感谢!

编辑:

好的,这就是我的简单代码:

function Product(name, price) {
    this.name = name;
    this.price = price;
}

var register = {
    total: 0,
    list: [],

    add: function(Object, quant) {
        this.total += Object.price * quant;
        for (x=0; x <quant; x++) {
        this.list.push(Object);
        }
    },

undo: function() {
    var last_item = this.list[this.list.length - 1];
    this.total -= last_item.price;
    this.list.pop(this.list[this.list.length - 1]);
    },

print: function() {
    console.log("Super Random Market");
    for (x = 0; x < this.list.length; x++) {
        console.log(this.list[x].name + ": " + this.list[x].price.toPrecision(3));
    }
    console.log("Total: " + this.total.toFixed(2));
    }
}

var icecream_1 = new Product("Chocolate Icecream", 2.30);
var cake_1 = new Product("Chocolate cake", 4.00);

register.add(icecream_1, 5);
register.add(cake_1, 3);

register.print();

我试图建立一个收银机,我试图找出如何只用数量打印一次,而不是多次。

2 个答案:

答案 0 :(得分:4)

var randomArray = ["ball", "ball", "tree", "ball", "tree", "bus", "car"];
var itemCount = {};

randomArray.forEach(function(value){
    if(value in itemCount) itemCount[value] = itemCount[value] + 1;
    else itemCount[value] = 1;
});

然后你可以像这样引用数组中的“球”数:itemCount.ball这将返回3.

小提琴:http://jsfiddle.net/3XpXn/2/

缩小规模:

var randomArray = ["ball", "ball", "tree", "ball", "tree", "bus", "car"],
    itemCount = {};

randomArray.forEach(function(value){
    value in itemCount ? itemCount[value] = itemCount[value] + 1 : itemCount[value] = 1;
});

答案 1 :(得分:0)

以下代码应该有效。

    var randomArray = ["ball", "ball", "tree", "ball", "tree", "bus", "car"];       
        Array.prototype.findUniqueCount = function(){
          var collection = {}, i;   
          for (i = 0; i < this.length; i = i+1 ) {    
             collection[this[i]] = (collection[this[i]] || 0) + 1;
            }  
          return collection;
        };
console.log(randomArray.findUniqueCount());//{ ball: 3, tree: 2, bus: 1, car: 1 } 

检查此网址 https://coderpad.io/HEGY26FN