2

I have an array of objects. Note that "created" sometimes has the same value more than once. Also note that "status" is sometimes "0":

var array = [
{"created":"Jan 1","status":1},
{"created":"Jan 1","status":1},
{"created":"Jan 2","status":1},
{"created":"Jan 3","status":0},
{"created":"Jan 4","status":1},
{"created":"Jan 4","status":1}
];

I want a new a new array of objects like this:

var newArrayA = [
{"Jan 1":2},
{"Jan 2":1},
{"Jan 3":0},
{"Jan 4":2}    
];

OR a multidimensional array like this (I'm not sure which is better for D3.js):

var newArrayB = [
["Jan 1",2],
["Jan 2",1],
["Jan 3",0],
["Jan 4",2]    
];

So, when "status" is "1", it counts the number of "created" that are the same. And when status is "0", that is also included.

How do I do this? Here's what I have so far JSFIDDLE. Is this how to approach it? Or am I missing some simple solution? Thanks!

  • just found the second block of code here. investigating... http://stackoverflow.com/questions/17313268/find-the-number-of-occurrences-a-given-value-has-in-an-array –  Jun 10 '15 at 18:13

1 Answers1

1

D3 would cope with either result format - it does slightly depend on what you want to do with it. Regardless, here is some example code for generating either format:

var result = {};
array.forEach(function(i) {
    if (!result.hasOwnProperty(i.created)) {
        result[i.created] = 0;
    }
    if (i.status === 1) {
        result[i.created] += 1;
    }
});

var newArrayA = Object.keys(result)
                      .map(function(k) {
                          var o={};
                          o[k] = result[k];
                          return o;
                      })

var newArrayB = Object.keys(result)
                      .map(function(k) { return [k,result[k]] })
knolleary
  • 9,777
  • 2
  • 28
  • 35
  • Thank you so much!! You have much better logic and helped me a lot with the syntax. Super awesome thanks to you! –  Jun 10 '15 at 19:07
  • [Answered JSFIDDLE](https://jsfiddle.net/airwwwave/9dyxskbd/) for inspecting in console –  Jun 10 '15 at 19:58