0

Consider this code that is accessing the data of a javascript object.

animalData.animal[i].type

'animal' : [ 
  {'type':'dog', 'colour':'brown'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'orange'},
  {'type':'frog', 'colour':'green'},
  {'type':'cat', 'colour':'pink'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'black'},
  {'type':'dog', 'colour':'yellow'}
]

Using modern JS how can I transform the above into another array of objects that looks like this. eg. shows a count of each and removes the duplicates?

[
  {'type':'dog', 'count':'4'},
  {'type':'cat', 'count':'3'},
  {'type':'chicken', 'count':'2'},
  {'type':'frog', 'count':'1'},
]
0

1 Answer 1

1

You can reduce it and take Object values:

var data=[ {'type':'dog', 'colour':'brown'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'orange'}, {'type':'frog', 'colour':'green'}, {'type':'cat', 'colour':'pink'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'black'}, {'type':'dog', 'colour':'yellow'}];

var result = Object.values(data.reduce((acc, {type})=>{
  acc[type] = acc[type] || { type, count:0 };
  acc[type].count += 1;
  return acc;
},{}));

console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the reply! but my data is part of a larger javascript object and i can't seem to the get the above to work.. animalData.animal[i] for example is where all the animal data is within the object
@TimmyLee, the answer is according to your expected output. How you want output to be?
my bad.. i positioned the code above below another transformation on that array.. so it was no longer an array but a string of values! it works! many thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.