A guide on sorting an array of objects by their frequency within the array

My goal is to analyze an array of user objects, some of which are duplicated. The objective is to determine the frequency of each unique user object within the array and reorganize them so that the most frequently occurring user comes first while the least common user is placed at the end.

const users = 
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c4c1dbc9e8cfc5c9c1c486cbc7c5">[email protected]</a>", createdAt: 1593894321997},
 
   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cdced4c8c8e7c0cac6cecb89c4c8ca">[email protected]</a>", createdAt: 1592452421714},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6aca3a8a8afa386a1aba7afaae8a5a9ab">[email protected]</a>", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e12170d1f3e19131f1712501d1113">[email protected]</a>", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d464c5a44464c6d4a404c4441034e4240">[email protected]</a>", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fdf2f9f9fef2d7f0faf6fefbb9f4f8fa">[email protected]</a>", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c70756f7d5c7b717d7570327f7371">[email protected]</a>", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630802140a080223040e020a0f4d000c0e">[email protected]</a>", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fe5eae1e1e6eacfe8e2eee6e3a1ece0e2">[email protected]</a>", createdAt: 1593894227232}
]

To achieve this, I attempted using the countBy method from lodash:

const bestMatched = countBy(users, "handle");

After running the code, the result showed:

{lisa: 3, jisoo: 1, unnieJennie: 3, kawikaLovesKpop: 2}

However, it is important for me to retain access to the original users array with all key-value pairs intact.

Answer №1

To achieve this task, you can employ bitwise NOT. This is because ~undefined = -1, and an object is required to store the result:

const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})

Give it a try:

const users = 
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c9ccd6c4e5c2c8c4ccc98bc6cac8">[email protected]</a>", createdAt: 1593894321997},
 
   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa5a6bca0a08fa8a2aea6a3e1aca0a2">[email protected]</a>", createdAt: 1592452421714},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="08626d6666616d486f65696164266b6765">[email protected]</a>", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6cacfd5c7e6c1cbc7cfca88c5c9cb">[email protected]</a>", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b2b8aeb0b2b899beb4b8b0b5f7bab6b4">[email protected]</a>", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5cfc0cbcbccc0e5c2c8c4ccc98bc6cac8">[email protected]</a>", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb0b5afbd9cbbb1bdb5b0f2bfb3b1">[email protected]</a>", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91faf0e6f8faf0d1f6fcf0f8fdbff2fefc">[email protected]</a>", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c9c6cdcdcac6e3c4cec2cacf8dc0ccce">[email protected]</a>", createdAt: 1593894227232}
]

const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})

console.log({result})

If you require ordered data, utilize an array since objects are not inherently ordered.

const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})
Object.keys(result).sort((a,b)=>result[a]-result[b]).map(key=>({[key]:result[key]}))

Answer №2

Give this a shot:

let counterObject = {}

for (userInfo of userInfos){
    counterObject[userInfo.username] = 1 + (counterObject[userInfo.username] || 0)
}

console.log(counterObject)

Answer №3

const userList = 
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc90958f9dbc9b919d9590d29f9391">[email protected]</a>", createdAt: 1593894321997},
   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761c1f05191936111b171f1a5815191b">[email protected]</a>", createdAt: 1592452421714},
   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="49232c2727202c092e24282025672a2624">[email protected]</a>", createdAt: 1593894227232},
   // More user objects here...
]

let userCount = {lisa: 3, jisoo: 1, unnieJennie: 3, kawikaLovesKpop: 2}
userMap = new Map()
users.map(user => userMap.set(user.handle, user))
result = Object.entries(userCount).sort((a,b)=>b[1]-a[1])
.flatMap(obj =>Array(obj[1]).fill(userMap.get(obj[0])))

console.log(result)

Answer №4

It seems like the solution you were searching for has been found. Despite some initial JSON errors, everything appears to be in order now.

const users = [
  {
    id: '0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8',
    handle: 'lisa',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="721e1b011332151f131b1e5c111d1f">[email protected]</a>',
    createdAt: 1593894321997,
  },
  // Remaining user objects...
];

function groupUsers(jsonArray) {
  var groupedArray = [];
  jsonArray.map((item, index) => {
    if (item !== 'null') {
      var newUserGroup = [];
      var itemHandle = item.handle;
      jsonArray.map((i, ind) => {
        if (itemHandle === i.handle && itemHandle !== 'null') {
          newUserGroup.push(i);
          jsonArray.splice(ind, 1, 'null');
        }
      });
      jsonArray.splice(index, 1, 'null');
      groupedArray.push(newUserGroup);
    }
  });
  return groupedArray;
}

var finalUserGroups = groupUsers(users);

// Sorting the finalUserGroups by frequency of occurrence
finalUserGroups.sort(function(a,b){
  return b.length - a.length
})

console.log(finalUserGroups)

This code ensures that related objects are kept together for easy access to their properties using dot notation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the matrix in a semi-spiral pattern

I am working with a 3 by 5 matrix, filled with numbers from 1, presented as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The task is to print the values in a half-spiral order, starting from the bottom left vertically: 11 6 1 5 10 15 12 7 2 4 9 ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

Is there a way to create a password-like input in HTML that can also trigger keydown events?

Is there a way to record keyboard events on masked password input elements without compromising security? I want to assure everyone that my intentions are not malicious. I am simply looking for a way to analyze user behavior after informing them and ensur ...

Steps to create a typewriter effect using a collection of words

I managed to create a looping typewriter effect, but I'm facing an issue where the first word in the array is not being typed again after the first cycle. Additionally, I am seeing 'undefined' displayed after the last word before it repeats ...

Troubleshooting Java QuickSort on Array Overload

Can someone guide me on why I might be encountering a stack overflow issue in my quicksort algorithm code below? private int[] mergeArrays( int[] firstArray, int indexLower, int pivot, int indexMiddle, int[] secondArray ) { int[] merged = new ...

Having trouble showing an image with jQuery after it has been uploaded

Currently, I have a URL that shows an image upon loading. However, I want to provide the option for users to replace this image using a form input. My goal is to display the uploaded image as soon as it's selected so users can evaluate it. I'm a ...

Storing information from a table into LocalStorage

$('.new_customer').click(function () { var table = $("table"); var number = table.find('tr').length; table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" ...

Guide on incorporating a CARTO map into your react.js code

I'm currently facing a challenge as I attempt to connect a CARTO map (created using the CARTO builder) with react.js. My roadblock is with employing carto.js via cartoclient: this.cartoClient = new carto.Client({ apiKey: 'key', username: & ...

Advanced JavaScript function invocation

I have been learning JavaScript and I am struggling to understand the coding style I see in the code I read. I am familiar with the "old" way of writing JavaScript but I haven't come across any resources that explain this new way of creating and calli ...

Incorporate geographical data from a JSON file into my Google Maps application

Hey there, I'm a newbie on this forum and could really use your expertise. I've put together an html5 page with Google maps using the API key from Google (My code is shown below), it's working fine with a central marker in place and loads pe ...

Transferring data from client to server: Weighing the pros and cons of

When dealing with 1-5 variables on the client side that need to be sent to the server using AJAX (Post Method), there are two primary methods of getting them there. One option is to use JSON to encode and decode the variables, sending them as a JSON stri ...

various types of information in a grid

My data includes the following matrices: [[-0.96092685 1.16253848] [ 1.49414781 0.265738 ] [ 0.02689231 -1.09912591] ... [ 0.16677277 1.43807138] [-0.36808792 -0.03435113] [-0.3693595 0.44464701]] and another matrix like this: [-1 1 -1 -1 -1 ...

Issue in JavaScript on IE9: SCRIPT5022 error: DOM Exception - INVALID_CHARACTER_ERR (5)

I am encountering an error with the following line of code: var input2 = document.createElement('<input name=\'password\' type=\'password\' id=\'password\' onblur=\'checkCopy(th ...

Sails.js Unidirectional Association

I'm currently working on establishing a relationship between two MySQL tables in sails js. I went through the documentation regarding this topic which can be found here. However, I encountered an error message: error: Sending 500 ("Server Error") re ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

What is causing this JavaScript to not function properly? (window.scrollTop)

One CSS class called 'stuck-sm' is included, but the class 'stuck-md' is not currently being added. if ($(window).scrollTop() >= 285) { $('.something').addClass('stuck-sm'); } else if ($(window).scrollTop() > ...

Error 9 in Firebase: The function 'initializeApp' could not be located within the 'firebase/app' module

Since updating to firebase 9, I've been encountering issues with importing certain functions that were working fine on firebase 8. I've gone through the documentation and made necessary code improvements, but the error persists. This issue is not ...

Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked. As it stands now, whe ...

Node.JS displaying the asynchronous functionality with 'Promise' included in the returned data

Here is a node.js function call and function that I am having trouble understanding: var returned = checkCurrentProcesses() returned.then(() => { console.log(returned) }) function checkCurrentProcesses() { return new Promise(funct ...

Clicking on the textarea changes the cursor's position

I've been working on adding an emoji function, but I'm facing an issue. Whenever I select an emoji from the dropdown while having text in the textarea and the cursor placed at the beginning of the text, the emoji always gets added to the end like ...