bufo333
bufo333

Reputation: 85

Javascript function to count nested array of object properties possibly using reduce/map

I have a problem and I have looked at a few reduce questions on here and I just can't seem to wrap my head around a way to do this. I have an array of objects. Each object has the same properties, about 30 of them. Each of the properties has completely different types of information. I want to be able to create a new object/array easily. My example is below.

var array = [{parts: 12345, purchased: "yes", customerId: 12541},
             {parts: 12432, purchased: "no", customerId: 55514},
             {parts: 12345, purchased: "Yes", customerId: 44421}];

What I want to do is find a way to extract useful data depending on the type of information in the array. For example:

some_function(array) {
             ...
             return { parts: {uniquePart: 12345, timesListed: 2}};
             }
     }

I may also want to extend that returned object and count the number of times purchased was either yes or no. I have tried numerous approaches but I am thinking this is more a data model issue than a programming issue.

I am parsing this data off of strings of receipts. Once the plain text string is parsed I get a large 30 property object for each transaction. Some of the properties also are nested objects or arrays as well.

I want to correlate data across multiple transactions. Maybe I need to research a better way to approach this type of situation as a whole.

So I understand the question is a little vague but what I really want to know is what is the best way with the array given to end up with the following data structure:

{parts: {uniquePart: 12345, timeListed 2}}

I believe once I understand how to itterate through the nested array of objects and build the new object I can go from there. My current attempts using reduce have not yielded fruit.

array.reduce(acc,obj){return This is where I am a little lost}

Upvotes: 1

Views: 2229

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

This solution features Array.prototype.forEach, Object.keys and Array.prototype.map for a temporary object count and returns the wanted array with one object for every part.

function getCount(array) {
    var count = {};
    array.forEach(function (a) {
        count[a.parts] = (count[a.parts] || 0) + 1;
    });
    return Object.keys(count).map(function (k) {
        return { parts: { uniquePart: k, timesListed: count[k] } };
    });
}

var array = [{ parts: 12345, purchased: "yes", customerId: 12541 }, { parts: 12432, purchased: "no", customerId: 55514 }, { parts: 12345, purchased: "Yes", customerId: 44421 }];
document.write('<pre>' + JSON.stringify(getCount(array), 0, 4) + '</pre>');

Upvotes: 2

Related Questions