Develop a heap structure that ranks items according to the frequency of the competitor field

Testing a mockup variable:

[
        { competitor: 1 },
        { competitor: 1 },
        { competitor: 1 },
        { competitor: 1 },
        { competitor: 2 },
        { competitor: 3 },
        { competitor: 4 },
        { competitor: 4 },
        { competitor: 4 },
        { competitor: 5 },
        { competitor: 6 },
        { competitor: 6 },
        { competitor: 7 },
        { competitor: 7 },
        { competitor: 7 },
        { competitor: 8 },
        { competitor: 9 },
        { competitor: 10 },
        { competitor: 11 },
        { competitor: 12 },
      ]
    

Code snippet to group repeated items:

const splitRepeated = (array) => {
        let obj = array.reduce((res, curr) => {
            if (res[curr.competitor]) res[curr.competitor].push(curr);
            else Object.assign(res, { [curr.competitor]: [curr] });

            return res;
        }, {});
        return obj;
    };
    

Result of grouping:

{
        '1': [
            { competitor: 1 },
            { competitor: 1 },
            { competitor: 1 },
            { competitor: 1 }
        ],
        '2': [ { competitor: 2 } ],
        '3': [ { competitor: 3 } ],
        '4': [ { competitor: 4 }, { competitor: 4 }, { competitor: 4 } ],
        '5': [ { competitor: 5 } ],
        '6': [ { competitor: 6 }, { competitor: 6 } ],
        '7': [ { competitor: 7 }, { competitor: 7 }, { competitor: 7 } ],
        '8': [ { competitor: 8 } ],
        '9': [ { competitor: 9 } ],
        '10': [ { competitor: 10 } ],
        '11': [ { competitor: 11 } ],
        '12': [ { competitor: 12 } ]
    }
    

Now attempting to evenly distribute the repeated elements:

[{ competitor: 1 },{ competitor: 2 },{ competitor: 3 },{ competitor: 1 },{ competitor: 4 },{ competitor: 5 },{ competitor: 1 }]
    

Current attempt at distributing:

const spreadOrder3 = (array) => {
        let obj = splitRepeated(array);
        let objEntities = Object.entries(obj);
        console.log(obj);
        let newArray = objEntities.map((x) => x[1][0]).flat();
        let oldIndex = newArray.length;
        for (let e = 0; e < oldIndex; e++) {
            let each = Math.floor(oldIndex / objEntities[e][1].length);

            let counter = 0;
            for (let i = 0; i < objEntities[e][1].length; i++) {
                console.log(objEntities[e][1][i]);
                console.log((counter + 1) * each);
                newArray.splice((counter + 1) * each, 0, objEntities[e][1][i]);
                // newArray[(counter + 1) * each] = objEntities[e][1][i];
                counter++;
            }
        }
        return newArray;
    };
    

The current distribution is not satisfactory, looking for help to keep repeated elements together. Thank you.

Expected output:

Array length with unique elements: 12

competitor: 1 has 4 repeats then insert every 3 elements: 12/4 = 3

competitor: 4 has 3 repeats then insert every 4 elements: 12/3 = 4

competitor: 6 has 2 repeats then insert every 6 elements: 12/2 = 6

competitor: 7 has 3 repeats then insert every 4 elements: 12/3 = 4

Desired outcome:

[{ competitor: 1 },{ competitor: 2},{ competitor: 3 },{ competitor: 1 }, { competitor: 4 },{ competitor: 5 },{ competitor: 1 }]
    

Answer №1

To create a sorted array of grouped values based on their lengths, follow these steps:

Begin with an array containing indices for the final result and distribute values from the same group at equal distances.

Math.floor((indices.length - 1) / (a.length - 1))

Using the indices array, place the values in the result array accordingly and remove used indices until all values are distributed.

0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19  starting indices

1  1  1  1  2  3  4  4  4  5  6  6  7  7  7  8  9 10 11 12  original values
1                 1                 1                 1     d = 6
   4                       4                       4
      7                       7                          7
         6                                      6
            2  3     5  8        9    10 11 12              isolated values 

const
    data = [1, 1, 1, 1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 7, 7, 8, 9, 10, 11, 12],
    indices = [...data.keys()],
    groups = data.reduce((r, v) => ((r[v] ??= []).push(v), r), {}),
    result = Object
        .values(groups)
        .sort((a, b) => b.length - a.length)
        .reduce((r, a) => {
            const d = a.length === 1 ? 1 : Math.floor((indices.length - 1) / (a.length - 1));
            a.forEach((v, i) => r[indices.splice(i * d - i, 1)[0]] = v);
            return r;
        }, []);

console.log(...result);

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

Implementing Angular to activate the JavaScript 'click' event

I am attempting to initiate an 'onclick' event within an angular controller. <div id="galerie"> <h2>{{main.Page.title()}}</h2> <hr> <div class="row"> <div class="col-sm-4 col-xs-6" ng-repeat= ...

Using the Flow type checker with React library results in complications

I'm fairly new to JavaScript and React, so I appreciate your patience! I've recently started a project using create-react-app with React version 16.12.0. I installed a library that seems to be utilizing Flow. When attempting to use this library ...

Issue: The hydration process failed as the initial UI does not align with the server-rendered content when using useSession() along with react-bootstrap

I am currently utilizing next.js, react18, and next-auth. Within my login component, I have code that checks the session status and displays a login or logout link based on whether the user is logged in or not. import Link from 'next/link'; cons ...

Sliding panel for horizontal overflow

Currently, I am developing a web animation GUI that requires a sliding timeline area similar to this example: With a starting time of 0, there is no need to slide to negative times, but the ability to zoom in and slide side to side to view the entire time ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

The Express-Validator failing to validate

I'm currently working on a basic program with Express. I've integrated Express-Validator to perform validations on an EJS index file. Initialization: const {check, validationResult} = require('express-validator/check'); Implementatio ...

Encountering a Vue promise issue, I am currently facing a problem related to promises

Although my fetch method is successful with other API calls, I am encountering an error when fetching from this specific API. The error message states: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'json') Here&ap ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Setting up a secure HTTPS server using Node.js and Express.js

Currently in the process of setting up a HTTPS server using Node.js and Express.js. This is what I have so far: const filesystem = require('fs'); const express = require('express'); const server = express(); const http = require(&apos ...

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

Mesh is making an excessive number of draw calls

After importing some mesh from Blender using the three.js exporter from the utils folder, I noticed that it only has 3 materials but is utilizing 28 draw calls. Why is this happening? I expected it to use only 3 draw calls. View mesh image ...

How can one track an array based on specific criteria?

The array: let numberArray = [34,53,2,3,34,26,26,85,3,4,98,2,12]; How can I display every other item in the array in the output-panel: "34,2,34,26,3,98,12" How do I find and display numbers in the array that are lower than 10? What is the bes ...

Issue with using the :not() selector

My goal is to activate an event whenever a click occurs anywhere on the page except within a specific div. Here's how I started the code: $("html:not('#genre_div')").live("click", function(){ Unfortunately, it looks like the code is still ...

Python array multiplication algorithm

Struggling with calculating the product of my Python arrays. I have two arrays defined but encountering an issue. import numpy as np phi = np.array([[ 1., 1.],[ 0., 1.]]) P = np.array([[ 999., 0.],[ 0., 999.]]) np.dot(phi, P, phi.T) An error is t ...

A JavaScript code snippet to format a phone number in the pattern xx-xxxxxx

Please help me create a JavaScript function that can determine if the text in a textbox is a number. If it's not a number, I would like the function to focus on the textbox and change the format to look like this (xx-xxxxxx) when numbers are typed in, ...

Node-flickrapi utilizes the Flickr API Oauth to cache the oauth_verifier for authentication

I've been having a great experience using the authenticated Flickr API with Oauth and successfully implemented it with node.js thanks to the node-flickrapi NPM package. Whenever I run my code, the console prompts me to - add the following variables ...

A third-party script is causing disruption to my JavaScript code

My website has a 3rd party script that displays certain data, but when this script loads, it causes all of the JavaScript on any page it's included in to break. However, removing the script resolves the issue and my page functions properly. Is there ...

Tips for converting an asynchronous process to operate as a synchronous process

Hey there! Checkout this piece of code I have function executeBat(){ var process = require('child_process').exec; process('C:\\Temp\\tasks\\acis\\runme.bat', function(error, stdout, std ...

Tips for positioning dynamic high charts in a bootstrap row

I have implemented HighCharts for displaying charts on my website. Specifically, I am utilizing the chart type solidgauge. The charts are dynamic and I am looking to arrange them horizontally across the page. My goal is to align the charts in a layout sim ...

Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative. Current code snippet: var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxx ...