I am trying to do some mapping in JavaScript. What I am trying to do is I am trying to check if the type from arr
exists in datasetarr
, if existed, I get the index in datasetarr
and increment the quantity of that index. If not exists, I add in a new entry in datasetarr
. Here is my code:
var datasetarr = [];
var pos;
for(var i = 0; i < arr.length; i++){
console.log('unsorted ' + arr[i].type + ' ' + arr[i].quantity);
if(datasetarr.indexOf(arr[i].type) > -1){
pos = datasetarr.indexOf(arr[i].type);
datasetarr[pos].quantity += arr[i].quantity;
}else{
datasetarr.push({type: arr[i].type, quantity: arr[i].quantity});
}
}
for(var i = 0; i < datasetarr.length; i++){
console.log('sorted ' + datasetarr[i].type + ' ' + datasetarr[i].quantity);
}
The output should be:
kitchen appliance 20
home entertainment 8
batteries & lightings 4
home appliance 12
Then, I can get the type and quantity each and store into array for me to plot with chart.
However, with my code above, the things that I am getting is exactly the same as the unsorted one. Any ideas which part of my logic went wrong?
In general, I'd suggest lodash for this kind of stuff
In this particular case, however, a vanilla JS solution is just as easy:
Based on OP question:
And the clarification in comments:
I think the best and easy way to do it is doing exactly that, check if exist and act accordingly.
Expected output for
datasetarr
variable would be:You can write a generalized aggregate function like this, and call it by specifying the keys that categorize and aggregate, which are
type
andquantity
respectively. Lastly, you specify thereducer
function, which is just an aggregate sum,a + b
:Use objects for the grouping.
You can decompose the object if needed, through it into an array and sort it if required.
A little bit cleaner example, which might let you follow along a little bite better:
Here a solution of of
group
hiding the grouping, which than can hold your own implementation:Depending on your use case, you could also flatten the structure:
But it might make sense to have various maps in place:
To avoid information loss on aggregations, you could simply create a more complex data structure:
This creates an aggregation which also contains the subset of the input array, which allows you a more detailed view on the data.
That is because, Your If condition is only checking for index value in the resulted array datasetarr which is already empty for next value to be pushed,
So Your
will never execute. That is the reason you are getting the same output as input.