Arrange an array by the occurrence rate of its elements within objects contained in another array, using Javascript

I found the explanation to be rather complex. Essentially, my goal is to iterate through each object in the 'objects' array, analyze the 'choice' values, tally the frequency of each letter, and then arrange the original arrays based on occurrence rate.

Could someone provide the code to generate 'results' using 'letters' and 'objects'? I considered individually analyzing each object, creating a new array of choice values, calculating the frequencies, and sorting the letters array accordingly, but this seems like a lengthy process. I'm curious if there's a more concise code snippet that accomplishes what I'm aiming for.

const letters = ['a','b','c','d']

const objects = [ 
{ id: 1, choice: ['a','b'] }, 
{ id: 2, choice: ['a','b','c'] }, 
{ id: 3, choice: ['a','c'] }, 
{ id: 4, choice: ['a','c','d'] }
]; //Total count of appearances are: 'a':4, 'b':2, 'c':3, 'd':1 

const results = ['a','c','b','d'];  

Any pointers or recommendations? Thank you!

Answer №1

Follow these steps to achieve the desired outcome.

  • Iterate through the objects array.
  • Calculate and store the frequencies of each letter in an object.
  • Arrange the frequencies in descending order.
  • Extract the keys and add them to the result array.

const letters = ['a', 'b', 'c', 'd'];
const objects = [
{ id: 1, choice: ['a','b'] }, 
{ id: 2, choice: ['a','b','c'] }, 
{ id: 3, choice: ['a','c'] }, 
{ id: 4, choice: ['a','c', 'd'] }
];

const freqs = letters.reduce((acc, curr) => ({...acc, [curr]: 0}), {});
objects.forEach(({choice}) => choice.forEach(letter => {freqs[letter] !== undefined && freqs[letter]++}));

// Convert the freqs object into entries like [['a', 4], ['b', 2], ['c', 3]] and sort by the second index
const entries = Object.entries(freqs).sort((a, b) => b[1] - a[1]);

// Finally takes the keys from the sorted entries array.
const res = entries.map(([key, value]) => key);

console.log('res',res);
.as-console-wrapper {min-height: 100%!important; top: 0}

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

Only a single element in the array is being pushed by the JavaScript code, not all elements

Having an issue with my script where it is only returning one element out of a class that has 10 elements. Can anyone help me pinpoint the problem? `function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field- ...

How can you start a jQuery script following a triumphant Ajax callback?

Having some trouble getting jQuery to execute after a successful Ajax response. Even though I have it in the success callback, it doesn't seem to be working as expected. I came across a potential solution here, but I'm having difficulty understan ...

Display multiple series in Highcharts using JSON data, with each series having a unique style based on its

Is it possible to style different series on Highcharts based on JSON names? $.each(names, function (i, name) { $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?' ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Determine browser compatibility by evaluating the DOM Level

Can we easily determine which browser versions and above are compatible with a certain DOM level? ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Is there a way in jQuery to identify if a paragraph contains exactly one hyperlink and no other content?

I need to assign the 'solo' class to a link within a paragraph only if that link is the sole element in the paragraph. This example would have the 'solo' class: <p><a>I am alone</a></p> However, this example w ...

What is causing my array to display numbers that vary from the numbers originally assigned to it?

In my method, I am utilizing ASCII values of characters to calculate the absolute difference between adjacent characters in a string array. The result is stored in an integer array called 'arraynum2'. (The 'string' variable contains 4 c ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Setting the offset for panResponder with hooks: A step-by-step guide

While exploring a code example showcasing the use of panResponder for drag and drop actions in react native, I encountered an issue with item positioning. You can experiment with the code on this snack: The problem arises when dropping the item in the des ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Is there a method for redirecting my page to a specific href link without triggering a page reload?

This is my HTML code. <a href="http://127.1.1.0:8001/gembead/emstones.html?car=36">Car</a> I am trying to redirect to a specific page with parameters without fully reloading the current page. Is there a way to achieve this task? I believe the ...

Steps to retrieve the final page number from ngx-pagination with Angular

Is there a way to utilize Custom templates within ngx-pagination in order to ensure that the first and last buttons function properly when clicked? Currently, I have utilized pagination-template to accomplish this... How can I dynamically determine the la ...

Animated jQuery carousel with a timer countdown feature

Currently, I am developing a jquery slider/carousel to display various promotions. I am seeking a method to indicate the time left until the next promotion appears. Similar to the flash promo on this website: Do you have any suggestions? ...

What steps do I need to follow to integrate Vue.js into my Laravel Project?

I am familiar with Laravel and I have been attempting to incorporate Vue.js into my projects, but I am encountering some difficulties. Initially, I made sure to install Node.js and npm. Now, I am trying to use the command 'npm run watch' to chec ...

Unable to access style property, encountering error on separate page

Once again, I'm feeling a bit lost on where to go with this coding issue. It seems quite basic, but I'm struggling to pinpoint the problem. My goal is to hide several IDs, and while it does work, I keep encountering an error: Uncaught TypeError: ...

Error: Unable to access the property 'existsSync' since it is undefined - Creating Web Applications using Node.js and Express.js by Ethan Brown - Chapter 13

I am brand new to GitHub and the MEAN (mongodb, express, angular, node.js) stack. I am currently working through a book by Ethan Brown called 'Web Development with Node and Express', and he has provided a Git repository for me to clone and follow ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

Looking for a way to sort through data using the current time as a filter

In my possession is an object presented below: const user = { id: 3, name: "Clark Kent", mobileNumber: "1234567892", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d40595548545d674d4b ...