1. без уменьшения.
const items = [
{
id: 1,
type: 'PEPSI',
},
{
id: 1,
type: 'PEPSI',
},
{
id: 1,
type: '7UP',
},
{
id: 1,
type: 'FANTA',
},
{
id: 2,
type: 'FANTA',
},
{
id: 2,
type: '7UP',
},
{
id: 2,
type: '7UP',
}
];
const groupBy = (objectArray, property) => {
return objectArray.reduce(function (total, obj) {
let key = obj[property];
if (!total[key]) {
total[key] = 0;
}
total[key]+=1;
return total;
}, {});
}
let groupedArray = groupBy(items, 'type');
console.log(groupedArray);
2. без уменьшения.
const items = [
{
id: 1,
type: 'PEPSI',
},
{
id: 1,
type: 'PEPSI',
},
{
id: 1,
type: '7UP',
},
{
id: 1,
type: 'FANTA',
},
{
id: 2,
type: 'FANTA',
},
{
id: 2,
type: '7UP',
},
{
id: 2,
type: '7UP',
}
];
const compressArray = original =>{
var compressed = [];
var copy = original.slice(0);
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (copy[w] && original[i].type == copy[w].type) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i].type;
a.count = myCount;
compressed.push(a);
}
}
return compressed;
};
var counter = compressArray(items);
console.log(counter);