最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Array Map 2D array - Stack Overflow

programmeradmin4浏览0评论

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 use indexOf not in when working with arrays. Otherwise use an object if your keys are not numeric. – elclanrs Commented Mar 11, 2014 at 3:12
Add a ment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论