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;
});
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;
});
Share
Improve this question
asked Mar 11, 2014 at 3:08
codeBarercodeBarer
2,3989 gold badges48 silver badges79 bronze badges
1
-
1
You don't need an extra array when you use
map
, just return something. Also you want to useindexOf
notin
when working with arrays. Otherwise use an object if your keys are not numeric. – elclanrs Commented Mar 11, 2014 at 3:12
1 Answer
Reset to default 5You 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