मान लीजिए, हमारे पास इस तरह की वस्तुओं की एक सरणी है -
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
]; हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना है जो वस्तुओं की एक ऐसी सरणी लेता है। फ़ंक्शन को वस्तुओं से 'मान' और 'प्रकार' कुंजियों को हटा देना चाहिए और उनके मूल्यों को संबंधित वस्तुओं में कुंजी मान जोड़े के रूप में जोड़ना चाहिए।
इसलिए, उपरोक्त इनपुट के लिए आउटपुट इस तरह दिखना चाहिए -
const output = [
{ 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 },
{ 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45}
]; आउटपुट
इसके लिए कोड होगा -
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];
const groupArray = (arr = []) => {
const res = arr.reduce(function (hash) {
return function (r, o) {
if (!hash[o.name]) {
hash[o.name] = { name: o.name, flight: o.flight };
r.push(hash[o.name]);
}
hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
return r;
}
}(Object.create(null)), []);
return res;
};
console.log(groupArray(arr)); आउटपुट
और कंसोल में आउटपुट होगा -
[
{ name: 'JON', flight: 100, uns: 12, sch: 35 },
{ name: 'BILL', flight: 200, uns: 33, sch: 45 }
]