skip to Main Content

assume i have an array of objects the following

const objects = [{ total: 2 }, { total: 5 }, { total: 1 }, { total: 8 },{ total: 2 },{ total: 3 },{ total: 8 },{ total: 1 },{ total: 2 }];

what would be the best way to calculate what is the total with most instances? it our case it would be 2 as it appears more than all the rest.

function findTotalWithMostInstances(arr) {
  const frequency = arr.reduce((acc, obj) => {
    const total = obj.total;
    acc[total] = (acc[total] || 0) + 1;
    return acc;
  }, {});

  let totalWithMostInstances;
  let highestFrequency = 0;

  for (const total in frequency) {
    if (frequency[total] > highestFrequency) {
      totalWithMostInstances = total;
      highestFrequency = frequency[total];
    }
  }

  return parseInt(totalWithMostInstances);
}

make it more efficient

2

Answers


  1. There can be more than one total that occurs the same number of times. This would give you a list sorted from most instances to least:

    const objects = [
      { total: 2 }, { total: 5 },
      { total: 1 }, { total: 8 },
      { total: 2 }, { total: 3 },
      { total: 8 }, { total: 1 },
      { total: 2 }
    ];
    
    console.log(
      Object.entries(objects.reduce((a, { total }) =>
        (a[total] = (a[total] || 0) + 1) && a, {}))
        .sort((a, b) => b[1] - a[1])
    );

    Explanation: Reducing into an object working as a hash table with counters for each value of total. Using Object.entries to convert the object into an array of arrays. Sorting the array based on occurences.

    Login or Signup to reply.
  2. You could reduce with a single loop and an object with additional max and values properties.

    In each iteration increment the has and check if the count is greater than max, then get a new array for values with total as single item and increment max. If max and count is equal, just add total to values.

    Finally return only values property.

    const
        findTotalWithMostInstances = array => array
            .reduce((acc, { total }) => {
                acc[total] = (acc[total] || 0) + 1;
                if (acc.max < acc[total]) {
                    acc.values = [total];
                    acc.max++;
                } else if (acc.max === acc[total]) {
                    acc.values.push(total);
                }
                return acc;
            }, { max: 0 })
            .values,
        objects = [{ total: 2 }, { total: 5 }, { total: 1 }, { total: 8 },{ total: 2 },{ total: 3 },{ total: 8 },{ total: 1 },{ total: 2 }];
    
    console.log(findTotalWithMostInstances(objects));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search