Ich habe ein Array wie dieses:
const fruits = [
{ fruit: 'apple', year: 2018 },
{ fruit: 'apple', year: 2018 },
{ fruit: 'banana', year: 2018 },
{ fruit: 'orange', year: 2018 },
{ fruit: 'apple', year: 2017 },
{ fruit: 'apple', year: 2016 }
];
Jetzt möchte ich dieses Array reduzieren, um zu sehen, wie viele Früchte es jedes Jahr gibt und wie viel die Summe ist. Damit das Ergebnis so aussieht:
const result = [
{ year: 2018, apple: 2, banana: 1, orange: 1 total: 4 },
{ year: 2017, apple: 1, total: 1 },
{ year: 2016, apple: 1, total: 1 }
];
Ich habe es mit Reduzieren versucht, aber ich konnte nicht herausfinden, wie ich es basierend auf dem Jahr gruppieren soll. Vielleicht gibt es auch einen Lodash-Helfer?
1
Nibor
19 Apr. 2018 im 13:07
3 Antworten
Beste Antwort
Verwenden Sie Object.values
und reduce
var output = Object.values(fruits.reduce( (a,c) => {
a[c.year] = a[c.year] || { year : c.year };
a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
return a;
},{}));
Demo
var fruits = [{
fruit: 'apple',
year: 2018
},
{
fruit: 'apple',
year: 2018
},
{
fruit: 'banana',
year: 2018
},
{
fruit: 'orange',
year: 2018
},
{
fruit: 'apple',
year: 2017
},
{
fruit: 'apple',
year: 2016
}
];
var output = Object.values(fruits.reduce((a, c) => {
a[c.year] = a[c.year] || {
year: c.year
};
a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
return a;
}, {}));
console.log(output);
4
gurvinder372
19 Apr. 2018 im 10:13
Mit array#reduce
können Sie Ihre Daten nach Jahr gruppieren und das Auftreten von Früchten in einem Objektakkumulator zählen. Holen Sie sich dann alle Werte von diesem Objekt mit Object.values()
const fruits = [ { fruit: 'apple', year: 2018 }, { fruit: 'apple', year: 2018 }, { fruit: 'banana', year: 2018 }, { fruit: 'orange', year: 2018 }, { fruit: 'apple', year: 2017 }, { fruit: 'apple', year: 2016 } ],
result = Object.values(fruits.reduce((r,{fruit, year}) => {
r[year] = r[year] || {year};
r[year][fruit] = (r[year][fruit] || 0) + 1;
r[year]['total'] = (r[year]['total'] || 0) + 1;
return r;
},{}));
console.log(result);
1
Hassan Imam
19 Apr. 2018 im 10:15
Sie können ein Array als Ergebnismenge verwenden, das die angegebene Reihenfolge des Jahres beibehält.
var fruits = [{ fruit: 'apple', year: 2018 }, { fruit: 'apple', year: 2018 }, { fruit: 'banana', year: 2018 }, { fruit: 'orange', year: 2018 }, { fruit: 'apple', year: 2017 }, { fruit: 'apple', year: 2016 }],
result = fruits.reduce((r, { year, fruit }) => {
var item = r.find(o => o.year === year);
if (!item) {
r.push(item = { year });
}
item[fruit] = (item[fruit] || 0) + 1;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
0
Nina Scholz
19 Apr. 2018 im 10:50