3

I'm trying to aggregate the array (arr) below so that I get an output such as:

Desired Output: [['2011-04-11','Open',6],['2011-04-11','Closed',4]]

but I'm getting: Output: [2011-04-11,Open: 6, 2011-04-11,Closed: 4]

How can I take the javascript array map and convert to desired out.

Source code excerpt:

var arr = [
    ['2011-04-11', 'Open'],
    ['2011-04-11', 'Closed'],
    ['2011-04-11', 'Closed'],
    ['2011-04-11', 'Open'],
    ['2011-04-11', 'Open'],
    ['2011-04-11', 'Open'],
    ['2011-04-11', 'Closed'],
    ['2011-04-11', 'Closed'],
    ['2011-04-11', 'Open'],
    ['2011-04-11', 'Open']
];

var hist = [];
arr.map(function(a) {
   if (a in hist)
      hist[a]++;
   else
      hist[a] = 1;
});
1
  • 1
    You don't need an extra array when you use map, just return something. Also you want to use indexOf not in when working with arrays. Otherwise use an object if your keys are not numeric. Commented Mar 11, 2014 at 3:12

1 Answer 1

5

You can use [].reduce() instead:

var result = function() {
    var hist = {};

    return arr.reduce(function(previous, current) {
        if (current in hist) {
            previous[hist[current]][2]++;
        } else {
            previous[hist[current] = previous.length] = current.concat(1);
        }
        return previous;
    }, []);
}();

During the reduce operation, it uses hist to keep track of where each item can be found in the new array that's being built.

If the item already exists, it will increase its frequency element (third element). If the item does not yet exist, it will set its frequency to 1 and update hist to the position of the new item.

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Clever. I came up with console.log(arr.reduce(function(tillNow, currentItem) { tillNow[currentItem] = (tillNow[currentItem] || 0) + 1; return tillNow; }, {})); and got stuck :'(

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.