Adding a collection of items to an array in preparation for organizing

Realizing that sorting objects is not feasible - despite the necessity of having the object values sorted - I conclude that the only option is to move the object array content into a new array for sorting purposes.

The following code generates the output shown below without utilizing any array function:

https://i.sstatic.net/cnGLQ.png

This represents my code snippet:

var aveArr = {};
var length = 0;
var q = d3.queue();
['insert csv here', 'insert another csv here'].map((c) => {
  q.defer(d3.csv, c);
  length += 1;
});

q.awaitAll(function(d, csvs){
    var selection = d3.merge(csvs);

    selection.map((d,i) => {
      aveArr[d.word] = {
        sum: 0,
        average: 0,
    };  

    var obj = aveArr[d.word];
    obj.sum += +d.frequency;
    obj.average = obj.sum / length;
});

  console.log(aveArr); 

});

I solely require the word and average values to appear in the console, followed by sorting the averages.

I came across this resource on pushing data to arrays, but unfortunately, it didn't work for me.

Answer №1

Currently, you are treating the 'array' as an object by assigning keys to it. My suggestion is to restructure the data so that it is a genuine array with predefined fields. This will make sorting and transforming the data much simpler:

//source data
const data = [
  { name: "0", sum: 0, average: 0 },
  { name: "001", sum: 0, average: 0 },
  { name: "00", sum: 1, average: 0.5 },
  { name: "01", sum: 0, average: 0 },
  { name: "1", sum: 11, average: 5.5 },
  { name: "1am", sum: 0, average: 0 },
  { name: "1pickford", sum: 0, average: 0 },
  { name: "1pm", sum: 0, average: 0 },
  { name: "1pm2", sum: 0, average: 0 },
  { name: "1st", sum: 3, average: 1.5 },
  { name: "1x", sum: 2, average: 1 },
  { name: "1xbet", sum: 0, average: 0 }
];
const transformed = data
  //extracting only the name and average
  .map(({ name, sum, average }) => ({ name, average }))
  //sorting based on average
  .sort((a, b) => a.average - b.average);

console.log(transformed);

Answer №2

Are you interested in preserving the existing structure of your object?

const data = {
  '0': { value: 0, total: 0 },
  '001': { value: 0, total: 0 },
  '00': { value: 1, total: 0.5 },
  '01': { value: 0, total: 0 },
  '1': { value: 11, total: 5.5 },
  '1am': { value: 0, total: 0 },
  '1pickford': { value: 0, total: 0 },
  '1pm': { value: 0, total: 0 },
  '1pm': { value: 0, total: 0 },
  '1st': { value: 3, total: 1.5 },
  '1x': { value: 2, total: 1 },
  '1xbet': { value: 0, total: 0 }
};

const extractedData = Object
  .keys(data).map(key => ({ label: key, total: data[key].total }));
  
const sortedData = extractedData.sort((left, right) => left.total - right.total);

console.log(sortedData);

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

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

vuex: The decision between using $store.commit and directly calling the function

Recently, I discovered an interesting technique where store mutation functions can be passed into HTML events. Here's an example: //In the template <input name="the_field" :value="the_field" @input="updateField"/> // In the component methods ...

Determine whether the elements in the master array match the elements in the child array

Checking for data presence in arrays: [ { "productDisplay": "ZXP 105", "productNumber": "WZDR 112" }, { "productDisplay": "ZXP 106", "productNumber": "WZDR 113" } ] ChildArray [{productDisplay:"ZXP 105", ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

Transforming JSON output into a string without any prior understanding

My AJAX function generates a JSON output which also includes unnecessary XML due to an error in the JSON WebService. To remove this XML, I have utilized JavaScript Regular Expressions. AJAX Function function setJsonSer() { var strWsUrl = 'https: ...

React Native animation encountered a rendering issue: Invalid transform scaleDisliked value: { "scaleDisliked": 1 }

While working on my react native app, I encountered an issue when trying to apply a transform:scale effect to an Animated.View component. I am using interpolate for this purpose, but unfortunately, I keep receiving the following error message: Render error ...

Server-side access to form data has been restricted

When I make a PUT request from the frontend, I am currently using the XMLHttpRequest and FormData API. However, on the server side, I am not receiving any data such as req.params, req.body, and req.query are all empty. Front-end Implementation var report ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

The initial state in NextJS fails to update when routing to the same page with different parameters

This particular project utilizes NextJS The structure of my page's URL is as follows: localhost:3000/first/second When I invoke getInitialProps on this page, the data retrieved from it is passed to the component and used to set the initial state li ...

Is there a way I can create an object in JavaScript by using an array of values as parameters instead of having to manually list them out?

Can I achieve this? My goal is to develop a universal factory function that can generate different types of factories with some commonalities. I aim to pass arguments as an array to the base factory, which would then potentially create a new object instanc ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

Using NextJS to Load Fonts from a Database

I've implemented a feature in my NextJS and Tailwind CSS app that allows users to select a theme with different color schemes and font options. The fonts available are all from Google Fonts. However, I'm facing an issue with loading the selected ...

Combining and replacing elements in an array

Is it feasible to combine two arrays and then replace the values of the original array? $originalArray = [1,2,3]; $newArray = [ 'first' => array_merge($originalArray, [4,5]), 'second' => array_merge($originalArr ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

What is the best way to switch between List and Grid view while automatically updating the image displayed?

**#Unique Component Implementation** import React from 'react'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import { makeStyles } from &apo ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

How can JavaScript be used to remove HTML tags from text while preserving a space between each line?

I found a helpful solution on Stack Overflow for removing HTML from text content. This is the method it suggests: function strip(html){ let doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || "&quo ...