Count occurrences of array objects

I'm looking to create an array of counts based on the occurrences of the same object within a different array. So far, my code looks like this:

var dates = [];
$.each(items, function (i, item) {
    dates.push(item.date);
});

which returns:

['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09']

After that, I'd like to end up with an array that looks like this:

[2,1,1,3]

Any help would be much appreciated!

Answers:

Answer

I would use a key/value counting approach where the date is the key and the value is the number of times it appears like so:

var counters = {};
$.each(dates, function(i, date) {
   counters[date] = counters[date] ? counters[date] + 1 : 1;
});

This approach assumes the dates will all be following identical formats of course.

Edit:

http://jsfiddle.net/wMR9x/2/

Then you can loop over it like so and simply join the results into another array:

var finalCounts = [];
var i = 0;
for(var key in counters)
    finalCounts[i++] = counters[key];
Answer
var dates=['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09'];
var count={};
var count_array=[];
for (i in dates){
    count[dates[i]] =count[dates[i]]?count[dates[i]]+1:1;
}

for (i in count){
   count_array.push(count[i]);
}
console.log(count_array);

jsfiddle

Answer

Try the countBy function in underscore.js:

_.countBy(dates,_.identity);

That will return an object of the form

{'2013/03':2, ...}

If you want to retrieve just the counts from that object, use the _.values function.

Answer

Try

var src = ['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09'];

var cnts = [];
for(var i = 0; i < src.length; i++){
    var val = src[i];
    var count = 1;
    while( val == src[i + 1]){
        count++;
        i++;
    }
    cnts.push(count)
}

Demo: Fiddle

Answer

You can use push method of the javascript array to achieve this

var arr = ['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09'];
var x = [],y = [], prev;
for (var i = 0; i < arr.length; i++) {
    if (arr[i] !== prev) {
        x.push(arr[i]);
        y.push(1);
    } else {
        y[y.length - 1]++;
    }
    prev = arr[i];
}
console.log(y);

JSFiddle

Answer

You can count the recurring values efficiently by using a map to keep track of the values you've already seen like this:

var data = ['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09'];

var map = {};
var sequence = [];
for (var i = 0; i < data.length; i++) {
    var item = data[i];
    if (map[item]) {
        map[item]++;
    } else {
        map[item] = 1;
        sequence.push(item);
    }
}

var output = [];
for (i = 0; i < sequence.length; i++) {
    output.push(map[sequence[i]]);
}

// output contains [2,1,1,3]

Working demo: http://jsfiddle.net/jfriend00/rQ7KB/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.