Organizing dynamic arrays using ECMAScript 2015

Currently, I am manipulating and reordering an array using data from a webpage. Initially, I reordered my array of objects based on a separate "sorting array" order. The original array looked like this:

[  
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"eBay",
      "providerName":"ebay",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"Cheap-Coilovers.co.uk",
      "providerName":"pricerunner",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"House of Fraser",
      "providerName":"connexity",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"notonthehighstreet.com",
      "providerName":"connexity",
      "needProcessing":false
   }
]

I then utilized my sort function on this array:

function compare(a, b) {
    let sortingArr = ['connexity', 'ecn', 'kelkoo', 'nexttag', 'pricerunner', 'shopping', 'ebay'];

    if (sortingArr.indexOf(a.providerName) < sortingArr.indexOf(b.providerName)) {
       return -1;
    }
    if (sortingArr.indexOf(a.providerName) > sortingArr.indexOf(b.providerName)) { 
       return 1;
    }
  return 0;
}
retailersOrdered.sort(compare);

This successfully orders the array of objects according to the sorting array, achieving the desired effect:

[  
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"House of Fraser",
      "providerName":"connexity",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"notonthehighstreet.com",
      "providerName":"connexity",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"Cheap-Coilovers.co.uk",
      "providerName":"pricerunner",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"eBay",
      "providerName":"ebay",
      "needProcessing":false
   }
]

Now, my goal is to further refine this by ordering the array in a "round robin" fashion. This entails selecting the first object with providerName "connexity," followed by the first object with providerName "pricerunner," and then the first object with providerName "ebay," looping back to the start for subsequent iterations. The desired output would be:

[  
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"House of Fraser",
      "providerName":"connexity",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"Cheap-Coilovers.co.uk",
      "providerName":"pricerunner",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"eBay",
      "providerName":"ebay",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"notonthehighstreet.com",
      "providerName":"connexity",
      "needProcessing":false
   }
]

The challenge lies in dynamically building up this array with varying numbers of objects per provider. Any suggestions or knowledge of es2015 functionalities that could assist in accomplishing this dynamic sorting process would be greatly appreciated.

Answer №1

The concept involves merging arrays together one element at a time in round robin order. This is achieved by organizing the providerNames, grouping items by providerName, and then adding the correct element to a new array for output. Take a look at this example:

var data = [  
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"eBay",
      "providerName":"ebay",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"Cheap-Coilovers.co.uk",
      "providerName":"pricerunner",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"House of Fraser",
      "providerName":"connexity",
      "needProcessing":false
   },
   {  
      "domain":"www.exampleurl.com/redirect",
      "retailerName":"notonthehighstreet.com",
      "providerName":"connexity",
      "needProcessing":false
   }
];

var providerNameIndex = 0;
// group objects by provider name
var groupedByProviderName = data.reduce(function (result, current) {
    if (!result[current.providerName]) {
        result[current.providerName] = [];
    }
    result[current.providerName].push(current);
    return result;
}, {});

// get providerNames in use, sorted according to specified sortingArr
var providerNames = Object.keys(groupedByProviderName).sort(function (a, b) {
    let sortingArr = ['connexity', 'ecn', 'kelkoo', 'nexttag', 'pricerunner', 'shopping', 'ebay'];
    if (sortingArr.indexOf(a) < sortingArr.indexOf(b)) {
      return -1;
    }
    if (sortingArr.indexOf(a) > sortingArr.indexOf(b)) { 
      return 1;
    }
  return 0;
});

function stitch (obj) {
    var results = [];
    // continue until all items have been included in the new array
    while(providerNames.some(name => obj[name].length)) {
        // loop through provider names
        var providerName = providerNames[providerNameIndex % providerNames.length];
        // if there are still items in the array, add the first item to the new array
        if(obj[providerName].length) {
            results.push(obj[providerName].shift());
        }
        // move to the next provider name in sequence
        providerNameIndex++;
    }
    
    return results;
}

console.log(stitch(groupedByProviderName));

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

What is the best way to handle the select event for a jQuery UI autocomplete when there are images involved?

Looking for help with creating an autocomplete feature with images on this jsfiddle. Despite trying to capture the event when a user selects an image, it doesn't seem to work properly: $("#input").autocomplete({ //source: tags, so ...

JavaScript 'Post' Request Triggered an Error

I've been encountering a "Bad Request" error while attempting to make a POST request. I would greatly appreciate it if someone could point out where I may have gone wrong. function mkSentiTopics() { dta['n_clusters'] = 3; $.ajax({ ...

How come I am unable to reach the window in my Next.js application's '_app.js' file?

In my Next.js application, I am trying to implement a feature where the app loads and then checks for network access using a custom modal dialog that alerts the user if they lose internet connection. I have set up an _app.js file in my application to estab ...

Unlocking the potential of Object[value] in JavaScript/jQuery: A guide to extracting its value

I have a table named 'mytable' with the following structure: <tr> <td><input type="checkbox" name="check[]" value="11"></td> <td>11</td> <td>2014-11-06 18:49:26</td> < ...

validate that the input contains only numbers within the range of 5 to 60

I need to validate inputted numbers within the range of 5-60. <div class="col-md-3"> <input type="text" name="gd_time" id="gd_time" placeholder="Enter a number between 5 and 60 " class="form-control"> </div> The script I have attemp ...

Displaying or concealing list elements in Angular 6

I am working on a simple Angular app that displays a list of items. I want the behavior to be such that when the first item in the list is clicked, its description (card) should be displayed. And, if the second item is clicked and its description is displa ...

Tips for retrieving the value of a table cell when the checkbox in the corresponding row is selected

Within my project, I am utilizing a table. The html code I am using is as follows: <table id="assTB" border="1px" cellspacing="0"> <colgroup> <col style="width:15%"> <col style="width:15%"> <col sty ...

Create a Three.js simulation of air flow passing through a cylindrical tube

I'm attempting to achieve the same fluid direction and airflow as demonstrated in this example: https://i.sstatic.net/TKLto.gif It seems that only the texture is in motion. I am struggling to comprehend how to simulate airflow in the right directio ...

Exploring the Possibilities of Socket.io Integration with Express 4 Across Multiple Pages: Dive Into Socket.io Sample Code

Just to clarify, I came across a similar question on Stack Overflow before posting this. However, the answer there was not clear to me and my query is slightly different. Thus, I am hoping for a more straightforward explanation. The Express Generator sets ...

Tips for including an external babel JS (ES6) file in an HTML document:

To include the babel js file in an HTML file, take a look at the code snippet below: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudfl ...

Saving Python array output as a CSV file

I need assistance with scraping data from a website using Python and BeautifulSoup. While I am able to extract the data and store it in a variable, I am encountering difficulties saving it to a CSV file. Here is the code snippet that I have been working on ...

How come my attempts to make my jQuery fade in upon button click aren't working?

#rock { display: none; position: relative; left: 49.4% } #paper { display: none; position: relative; left: 49%; bottom: 81px; } #scissors { display: none; position: relative; left: 48.14%; bottom: 162px; } #shoot { display: none; ...

What could be causing the discrepancy in the model value when using checkboxes in AngularJS?

Something strange is happening with my code. I have a checkbox in my view that has a directive to display its value when it changes. Surprisingly, it works fine in Firefox, showing the correct values. However, in other browsers like Chrome, it shows the op ...

Combining arrays in Numpy with identical rows but varying columns

I have an array that contains the same rows but different columns than other arrays. I checked the shape of the array and confirmed that they have the same rows. print ("Type x_test : actual",type(x_dump),x_dump.shape, type(actual), actual.shape, pred.sha ...

Divide the array object based on the "@" symbol

i am in possession of the following array object let old_array = { "valone": "facebook", "notification": "new message! @[email protected] @[email protected]" } i aim to extract all users with @ sign into a new array like displayed below le ...

Using promises and the fetch function to connect to a database

I am attempting to utilize promises with the fetch() function in order to access MongoDB from the front-end, but I am encountering some issues. var Promise = () => ( new Promise((resolve, reject) => { //perform certain actions, make requests ...

What is the quickest way to find and add together the two smallest numbers from a given array of numbers using JavaScript?

const getSumOfTwoSmallestNumbers = (numbers) => { const sortedNumbers = numbers.sort((a, b) => a - b); return sortedNumbers[0] + sortedNumbers[1]; } I encountered this challenge on Code Wars. My function to find the sum of the two smallest num ...

A single parallax transition designed exclusively for you

I am looking to add a unique parallax transition to my website, specifically one that features a nice scroll followed by a subtle bounce effect. For example, I want to incorporate an arrow that, when clicked, smoothly scrolls the user to the bottom of th ...

Unusual behavior observed while looping through an HTMLCollection returned by the getElementsByClassName method

After spending some time debugging, I discovered an issue with my function that changes the class of elements to modify their properties. Surprisingly, only specific elements were being affected by this change. It took me a while to troubleshoot and resolv ...

Issue with the datepicker not toggling properly in Angular-UI 0.11.0, only opens

I am struggling with implementing 2 datepickers using Angular UI version 0.11.0. Here is my HTML code: <span ng-if="periods.period == 10"> <input type="text" datepicker-popup="dd-MMMM-yyyy" ng-model="cdate.customStartDate" is-open="opened1" ...