JSFiddle - React, Tailwind, and code Playground

by John Wick

JavaScript

/* 
Create a JS function that will filter the variable favordrop all expired,
count the total items with the same merchant_id
and the result will looks output variable.

*/

var favordrop = [
	{
  	formal_name: 'sarah',
    merchant_id: 100,
    status: 'expired'
  },
  {
  	formal_name: 'sarah',
    merchant_id: 100,
    status: 'expired'
  },
	{
  	formal_name: 'bill',
    merchant_id: 200,
    status: 'expired'
  },
  {
  	formal_name: 'john',
    merchant_id: 300,
    status: 'expired'
  },
  {
  	formal_name: 'jackal',
    merchant_id: 400,
    status: 'active'
  },
];

function countExpiredByMerchant(favordrop) {
  // Filter out only the expired items
  const expiredItems = favordrop.filter(item => item.status === 'expired');

  // Count the occurrences of merchant_id
  const counts = {};
  expiredItems.forEach(item => {
    const key = item.formal_name;
    if (!counts[key]) {
      counts[key] = { formal_name: item.formal_name, count: 0 };
    }
    counts[key].count++;
  });

  // Convert the result to an array
  return Object.values(counts);
}

function getHighestCount(data) {
  return data.reduce((max, item) => (item.count > max.count ? item : max), data[0]);
}


var output = countExpiredByMerchant(favordrop);
console.log('result:', output);

var mostdata = getHighestCount(output);
console.log('most:', mostdata);




/* 
var output= [
  {
    formal_name: 'sarah',
    count: 2
  },
  {
    formal_name: 'bill',
    count: 1
  },
  {
    formal_name: 'john',
    count: 1
  }
]
 */