0

I have an array of objects which contain a "location" key. I already filtered and mapped the events array to a new visitedlocations array so that it only contains the locations. Now I can't figure out how to filter out the most occuring item in the visitedLocations array. Anyone have an idea?

How i filtered the events array:

 const visitedLocations = state.events
    .filter((event) => event.timeline.startDate < today)
    .map((event) => {
      return event.location;
    });
hoddypeak
  • 39
  • 1
  • 2
  • See https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements – danh Jul 20 '22 at 14:47
  • @hoddypeak I added an answer. Did you get a chance to look into the answer ? Hope it will help. – Debug Diva Jul 21 '22 at 14:17

3 Answers3

0

const arr = ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 1, 1, 2]
const unique = [...new Set(arr)] // Get unique values/keys
const counts = unique.map(key => (  // Make ojects with each key's count in original array
     {
       'key' : key,
       'count': arr.filter(element => element === key).length 
     } 
  ))
const sorted = counts.sort((a, b) => b.count - a.count) // Sort array based on counts
const mostOccurring = sorted[0] // Get first (largest) value

console.log('Unique: ', unique)
console.log('Counts: ', counts)
console.log('Sorted: ', sorted)
console.log('Most occuring: ', mostOccurring)
Brother58697
  • 2,290
  • 2
  • 4
  • 12
0

You can achieve that by using Array.reduce().

Live Demo :

const data = ['location 1', 'location 1', 'location 1', 'location 1', 'location 1', 'location 3', 'location 5', 'location 5'];

function freq(locationArr) {
  return locationArr.reduce((acc, curr) => {
    acc[curr] = -~acc[curr];
    return acc;
  }, {});
}

// Convert object into a 2D array.
const arr = Object.entries(freq(data));

// Now sorting the array based on the first index values. 
const sortedResult = arr.sort((a, b) => b[1] - a[1]);

console.log(sortedResult[0]);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

Considering the answer given by Matthew Flaschen here.

No need to use map, sort, reduce or filter functions.

It could be achieved using single for loop and couple of if...else statements.

Below given approach should be O(n).

function mostFrequentLocations(array)
{
    if(!array.length) return null;

    let modeMap = {};
    let maxEl = array[0];
    let maxCount = 1;

    for(let i = 0; i < array.length; i++)
    {
        let el = array[i];

        if(modeMap[el] === null) modeMap[el] = 1;

        else modeMap[el]++;
  
        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }

    return maxEl;
}
Shreeraj
  • 758
  • 1
  • 9
  • 27