Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz.

The topics rated as most important will contribute more questions to the pool of 20 questions. However, devising an algorithm to achieve this has proven to be quite challenging for me.

I have attempted to iterate over the parent topics array (which contains all topic objects with properties like name:str and question:[]). By determining the average number of questions needed to compile 20 questions from all the topics, I calculated any excess questions that may result.

For instance, if there are 6 topics, each should provide 3.3 questions on average. Rounded up to 4 questions per topic, we end up with 24 total questions - an overhead of 4.

My struggle lies in subtracting this overhead from the number of questions to be extracted from the least important rated topics, with the last item in the array being the least crucial.

function createWeightedQuestionBank(topicsArray) {

  // Object to store the returned questions.
  let questionsBanks = [];

  // Total number of questions desired in our quiz/question bank.
  const questionsLimit = 20;

  // Topics passed in through the topics Array - each Topic is an object with {name: "topicName", questions: [q1,q2,q3,q4]}
  const topics = topicsArray;

  if (topics) {

  // Number of topics in the topics array to be included in the question bank.
  // TODO: deciding which topics to include or exclude.
  const topicsAmount = topics.length;

  // Average amount of questions to be taken from each group to reach 20 questions (rounded up).
  const questionsAverage = Math.ceil(questionsLimit / topicsAmount);

  // Calculating projected number of questions when averaging from each group.
  const projectedQuestions = (questionsAverage * topicsAmount);

  let overhead;

  if (questionsLimit > projectedQuestions ) {
    overhead = questionsLimit - projectedQuestions;

  } else {
    overhead = projectedQuestions - questionsLimit;
  }

  let overheadVariance = overhead;

  for ( let i = 0; i < topics.length; i++) {
    const topic = topics[i];
    let pullAmount;

    if (topics.length - (overhead - 1) <= i) {
      pullAmount = questionsAverage - (overheadVariance - overhead);
      overheadVariance++;
    } else {
      pullAmount = questionsAverage;
    }
    console.log(topics.length - overhead);

Representation of the topics array.


 this.topics = [
      {
        name: 'testy',
        isSelected: false,
        questions:
          [
            'one',
            'two',
            'three',
            'one',
            'two',
            'three',
            'four',
          ]
    },
      {
        name: 'testy1',
        isSelected: false,
        questions:
          [
            'one',
            'one',
            'one',
            'one',
            'two',
            'three',
            'four',
          ]
    },
      {
        name: 'test2',
        isSelected: false,
        questions:
          [
            'one',
            'two',
            'three',
            'four',
          ]
    },
     ...
    ];

I am currently struggling to deduce how to substract the overhead of 4 from the last 3 topic question arrays. Instead of extracting 4 questions (the average amount), I aim to pull 3, 2, 1 questions from the three least important topics.

The desired outcome would be to pull 4 questions from some topics, followed by pulling 3, 2, 1 questions respectively from the less significant topics, totaling 20 questions. However, my current implementation is only logging 2 six times instead.

Answer №1

Actually, 3+2+1+4+4+4 is equal to 18, not 20 =)

If you want a calculation similar to 4+4+4+4+3+1, you can use the following code snippet:

const totalTopics = topics.length;
const questionsPerTopic = Math.ceil(questionsLimit / totalTopics);
const overhead = questionsPerTopic * totalTopics - questionsLimit;
const maxCanRemoveQuestions = questionsPerTopic - 1;
const singleQuestionedTopics = Math.floor(overhead / maxCanRemoveQuestions);
const remainingQuestionsToBeRemoved = overhead - singleQuestionedTopics * maxCanRemoveQuestions;

const calculateNumberOfQuestions = topicIndex => {
  if (topicIndex >= totalTopics - singleQuestionedTopics) {
    return 1;
  }

  if (topicIndex === totalTopics - singleQuestionedTopics - 1) {
    return questionsPerTopic - remainingQuestionsToBeRemoved;
  }

  return questionsPerTopic;
};

topics.flatMap(
  (topic, index) => {
    const amount = calculateNumberOfQuestions(index);

    return topic.questions.slice(0, amount);
  }
);

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 a comment system using Node.js and MySQL: A comprehensive guide

Hey there! I have some data that I want to use to create a hierarchical data example. { id_commentForum: 1, id_user: 1, id_thread: 1, comment: 'This is the First Comment', parent: 0, created_at: Wed Jun 22 2016 13:36:38 G ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

How can I insert my JavaScript functions into the JSF event queue for processing?

Is there a way to tap into the default JSF ajax(JS) event queuing system in order to execute events sequentially? I am attempting to align my JS events with this queue. Is there a global variable that can facilitate this synchronization? ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Why did the developers of Angular 2+ choose to use JavaScript Objects instead of Typescript Classes for defining Router routes?

When working with the Angular 2+ Router, the standard approach involves defining routes in the app-routing module. app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; ...

Utilizing Packery.js in AngularJS

Having some trouble trying to integrate Packery.js with my angularjs app. It seems like they are not working well together. I tried setting isInitLayout to false, but no luck. This is the (bootstrap 3) HTML code I am using: <div class="row" class="js ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

Why am I unable to utilize an array in this manner in JavaScript, and what is the method for accessing the array using a calculated number?

var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',]; var number = ["0","1","2","3","4","0","0","0"]; //some loop AccesNodes(number[1]); function AccesNodes(number){ console.log(number); // ...

Modify the contents of three div elements by incorporating JavaScript and ajax techniques

Currently working with rails 4 and JavaScript, I am faced with the following dilemma: I want to be able to alter the content of 3 specific divs on my page by clicking a single button. The values in these divs are being created by a Ruby function located in ...

Variable scope not properly maintained when there is a change in the Firebase promise

I am currently working on developing a controller function to handle signup submissions using Firebase. However, I've encountered an issue where the variables within the scope (controllerAs: $reg) do not seem to update correctly when modified inside a ...

Discovering the disparity amidst a pair of numpy arrays

After analyzing two arrays obtained from text files, it appears that they are identical. However, when comparing the arrays for equivalence - in terms of elements and shapes - they do not match. I followed the solution provided on this page. You can acces ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

Prevent form submission without JavaScript

While the issue is easy to grasp, it poses a challenge in implementation. I am encountering clients who disable their browser's Javascript by default, causing complications on my website. This is because my website sends ajax requests upon form submis ...

What is the best way to transfer the main-video-wrap div into the video-list-Wrapping div?

Thank you @Kathara for your valuable assistance I have successfully set up the video layout with a picture-in-picture mode option. When I click on a video to move it to the background, it works well. However, I am facing difficulty in moving the entire vi ...

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

What steps are necessary to configure karma webdriver launcher to utilize my selenium server or grid?

Could someone assist in identifying what is causing the Karma javascript test runner to have issues connecting to and utilizing my selenium grid/server? I currently have a functioning selenium grid setup that I utilize with python selenium bindings for co ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Implementing a list using display: inline-block without any specified order

Currently, I am immersed in a project that involves simulating an input using HTML and CSS. This input should be capable of executing a function like: my_cool_function(param0, param1, param2, param3). To accomplish this, I have constructed an unordered lis ...