Home > Back-end >  How to find the most occuring item in an array JS?
How to find the most occuring item in an array JS?

Time:07-21

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;
    });

CodePudding user response:

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)

CodePudding user response:

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]);

CodePudding user response:

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;
}
  • Related