Skip to content Skip to sidebar Skip to footer

How To Check If The Elements In An Array Are Repeated?

Ho everyone, I'm new to coding and I would like to know how do I find out whether an array has repeated objects or not regardless of their order without knowing what these objects

Solution 1:

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;
});

Then you can reference the number of "ball" in the array like this: itemCount.ball this will return 3.

Fiddle: http://jsfiddle.net/3XpXn/2/

Made it smaller:

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;
});

Solution 2:

The below code should work.

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 } 

check this url https://coderpad.io/HEGY26FN

Post a Comment for "How To Check If The Elements In An Array Are Repeated?"