Skip to content

Instantly share code, notes, and snippets.

@ms-fadaei
Created January 27, 2022 04:56
Show Gist options
  • Save ms-fadaei/d6b5ae76f423758a14daa4297d047dfd to your computer and use it in GitHub Desktop.
Save ms-fadaei/d6b5ae76f423758a14daa4297d047dfd to your computer and use it in GitHub Desktop.
Get get The Most Repetitive Item In Array
function getTheMostRepetitiveItem(items) {
const itemCounts = items.reduce((storageObj, item) => {
storageObj[item] = storageObj[item] || 0;
storageObj[item] += 1;
return storageObj;
}, {});
const sortedItems = Object.entries(itemCounts).sort(([keyA, valA], [keyB, valB]) => valB - valA);
return sortedItems[0]?.[0];
}
@alicivil
Copy link

alicivil commented Jan 28, 2022

function getTheMostRepetitiveItem(array) {
    let xx = array => (
        array.reduce(
            (acc, item) => {
                !(item in acc) ? acc[item] = 1 : acc[item]++;
                return acc;
            }
            , {})
    );
    let obj = xx(array);
    return Object.keys(obj).find(k => obj[k] === Math.max(...Object.values(obj)));
}

@ms-fadaei
Copy link
Author

@alicivil
I think this is a good idea to move Math.max(...Object.values(obj)) to the outside of the find method to increase performance.
I also recommend to you use more readable and meaningful words for your variables and functions names.
And finally, I don't know why you are creating a new function named xx?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment