How to group by attribute and count a huge list of items

Viewed 61

I have a list of crops with their attributes such as location where they were planted, planting technique used, experience and the crop planted itself. I have managed to group them by crop and coordinates (which represents location), but they are grouped separately. Here below is my code that groups and counts them.

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Reference messages collection
// var messagesRef = firebase.database().ref('Planting-Calendar-Entries');

database = firebase.database()

var ref = database.ref('Planting-Calendar-Entries');
ref.on('value', gotData, errData);

function gotData(data){
  console.log(data.val())
    var veggie = data.val();
    const counts = Object.values(veggie).reduce((counts, { Veg_planted, coordinates }) => ({
        ...counts,
        [Veg_planted]: (counts[Veg_planted] || 0) + 1,
        [coordinates]: (counts[coordinates] || 0) + 1
      }), {});
      console.log(counts);
  }
function errData(err){
    console.log('Error!');
    console.log(err)
}

Here is the output of the above code:

"-35.2294059, 173.9472028": 1
"-6.2087634, 106.845599": 3 ​ 
"-1.2920659, 36.8219462": 1 ​
"-0.3688967, 35.286286": 10 ​ 
"-0.3206518, 35.21896820000001": 1 ​
"-0.1634664, 35.5931397": 1 ​ 
"-0.3452364, 35.1519724": 2 
Ageratum: 3 
"Balloon Flower": 2
​Beetroot: 1
"Bells Of Ireland": 2
Broccoli: 1
Cabbage: 12

I would love them to be grouped and counted as below:

"-0.3688967, 35.286286", Cabbage: 8
"-1.2920659, 36.8219462", Cabbage: 2
"-0.3206518, 35.21896820000001", Broccoli: 1
"-0.3688967, 35.286286", Beetroot: 1
"-0.3452364, 35.1519724", Ageratum: 2

If you have an idea of what I can do, I will appreciate it. Thanks!

1 Answers

It looks like, you need to add Veg_planted to a combined key with coordinates.

Before the callback function:

 var space = ', '

Callback for reduce:

(counts, { Veg_planted, coordinates }) => {
    const key = [...coordinates, space, Veg_planted].join('');
    counts[key] = (counts[key] ||0) + 1;
    return counts;
}
Related