0

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 are yet? For example:

I create an empty array:

var random_array = [];

Then I use one function to push objects in that array, so I end up with:

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

In the array above we have:

3 balls, 2 trees, 1 bus, 1 car.

So how will I be able to know these repeated numbers? Should I use a for loop or what? Anyway, I'm new to coding so please bear with me. And thanks in advance!

Edit:

Ok, so here's my simple code:

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

I'm trying to build a cash register and I'm trying to find out how to only print the items once with its quantity, instead of multiple times.

wessy
  • 79
  • 4
  • 9
  • An object can't be repeated, as no two objects are the same? You're mixing up arrays, objects, strings, and undefined variables, so it's hard to understand what you're really asking ? – adeneo Aug 04 '14 at 19:25
  • This may be of interest to you: http://stackoverflow.com/questions/13486479/how-to-get-an-array-of-unique-values-from-an-array-containing-duplicates-in-java – Carl Aug 04 '14 at 19:27
  • Do you need to check for objects of the same type with the same property values or just objects of the same type? – Luka Aug 04 '14 at 19:27
  • welcome to coding, and welcome to stackoverflow. Its very difficult to help you because you didn't try anything or show anything you've already done. Our community is designed to help you learn, not do things for you. Try a loop. See if it works and then post it here if you're having trouble. – Cfreak Aug 04 '14 at 19:28
  • @Luka, Objects of the same type with the same property values. – wessy Aug 04 '14 at 19:30
  • jQuery or pure JavaScript? Which one would you like your solution in? – Luka Aug 04 '14 at 19:33
  • Do you want a count of the repeats, or an array that contains only unique items? – Thomas W Tupper Aug 04 '14 at 19:35
  • possible duplicate of [JavaScript - Count duplicates within an Array of Objects](http://stackoverflow.com/questions/10541068/javascript-count-duplicates-within-an-array-of-objects) – Erik Philips Aug 04 '14 at 19:57

2 Answers2

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

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;
});
Kolby
  • 2,775
  • 3
  • 25
  • 44
  • A nice solution to creating a unique array, but it isn't clear to me from the OP's statements if he wants that, or if he wants a count of occurrences. – Thomas W Tupper Aug 04 '14 at 19:34
  • @ThomasWTupper: It looks like he'd like to count duplicates: "3 balls, 2 trees..." etc. – Luka Aug 04 '14 at 19:35
  • oh I see. 1 second then. – Kolby Aug 04 '14 at 19:36
  • Thanks for the replies everyone, I'll try this thing that Kolby suggested. At any rate what I am trying to learn is how to build a simple cash register, so I'll update the OP with my code too. I wanna know why an element in the array repeats so I don't need to print it out X times, and I can instead, print it once with its quantity! – wessy Aug 04 '14 at 19:40
  • Updated the answer. The second bit of code will make an object that will have the number of duplications for each entry in the array. – Kolby Aug 04 '14 at 19:43
  • Your answer contains jQuery code under a question with no such tag. please exchange the `$.each` to a regular loop. – SeinopSys Aug 04 '14 at 19:48
  • Thanks again you too! I'll study this. – wessy Aug 04 '14 at 19:49
  • @DjDavid98 - Removed the jQuery. – Kolby Aug 04 '14 at 19:52
  • 2
    @Kolby Upvoted. I'd still suggest just using a normal `for` loop, but I'll leave that up to you. For OP: Please note that `Array.forEach` is not supported in Internet Explorer 8 and below. [ECMAScript 5 compatibility table](http://kangax.github.io/compat-table/es5/#Array.prototype.forEach) – SeinopSys Aug 04 '14 at 19:54
0

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