0

Similar to this question - Array value count javascript

How would I go about doing this, except with dynamic values?

var counts = []
var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];

How would I get a count of the duplicated array values? So how many 28/05/2013 etc. The dates are all dynamic, so I can't just search for set values. I just can't get my head around how I would do this.

I may just scrap this idea, and get the value count from the last 10 days or something... but this may come in handy later(if it is even possible to do this).

1
  • 4
    The solutions on the link you provided should work for you.. loop throught your array and invoke the function provided there. Commented May 28, 2013 at 9:27

3 Answers 3

3

This will do it:

var counts = {};
for (var i=0; i<dates.length; i++)
    if (dates[i] in counts)
        counts[dates[i]]++;
    else
        counts[dates[i]] = 1;

The result will be

> counts
{
    "28/05/2013": 3,
    "27/05/2013": 1,
    "26/05/2013": 1
}
Sign up to request clarification or add additional context in comments.

Comments

3

Make counts an object to perform duplicate detection in constant time.

var counts = {}

for (var i = 0; i < dates.length; i++) {
    var date = dates[i];
    if (counts[date] === undefined) {
        counts[date] = 0;
    }
    counts[date] += 1;
}

console.log(counts);

1 Comment

This works PERFECTLY. I think I understand how you're doing this.
0

Try like this

Updated

var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];
var findStr = "28/05/2013";
var indexs = dates.indexOf(findStr,0),count=0;
for (var i=0;i< dates.length;i++){
if (indexs >= 0){
    indexs = dates.indexOf(findStr,indexs + 1);
    count++;
}
}
alert(count);

See Demo

3 Comments

Try swapping the first date to 27 from 28, and you'll see that your code is rather broken.
I'm looking for a count of each duplicated element too, I'm afraid.
Better, but you still have a hardcoded value to find, so all you're doing is counting the number of occurrences of one value. Just sticking a loop around your code going foreach findstr in dates would work...but is also n*2 which is much slower than the solution needs to be. There is an easy optimisation you can add in then though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.