A Javascript function that accepts an object as input and outputs a list containing all the numerical values specified within the object

Create a function that accepts an object in the format {1: 4, 2: 10, 5:3} and outputs a list of numbers based on the key-value pairs in the object. Each pair specifies a number and how many times it should be included in the array.

Example: {3 : 10,5 : 2}

[3,3,3,3,3,3,3,3,3,3,5,5]

Handle cases where empty, null, undefined, or non-objects are passed into the function. In such scenarios, simply return an empty list, [].

Below is the code snippet I have been working on. I understand that a second loop is needed, but unsure about correctly populating the array with numbers as per their descriptions:

    var numObj = {1:4, 2:10, 3:5};

    function numDescribed(numObj) {
       var numOfNums = [];
       for (var x in numObj) {
          numOfNums.push(numObj[x]); //this creates an array of [4, 10, 5]
       } 
       for (var i = 0; i < numOfNums.length; i++) {
        numOfNums.
       }
    }

Answer №1

let numbers = { 2: 5, 4: 8 };

let result = [];

Object.keys(numbers).forEach((key) => {
    for (let j = 0; j < numbers[key]; j++) {
        result.push(key);
    }
});

document.write(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

Issue with Backbone.Marionette: jQuery document.ready not executing when on a specific route

I am dealing with a situation in my web application where the document.ready() block is not being executed when the page routes from the login button to the dashboard. I have an initialize() function that contains this block, but it seems like there is an ...

How to set up a MySQL database specifically for a quiz based on different "types"

I am a beginner in the world of HTML, PHP, JavaScript, and MySQL. I have developed a quiz using JavaScript and HTML, but now I believe I need a database to store all the questions and answers. I am currently using PHPMyAdmin to set up the database and tabl ...

Unable to incorporate an external JavaScript file via a static URL

I'm attempting to link an external javascript file using a static URL, like this: <script type="text/javascript" src="{{ url_for('static/js', filename='test.js') }}"></script> However, I am encountering the following ...

I am struggling to properly display the elements of an array in C#

I'm currently working on a school assignment and I've encountered some difficulties. The task at hand is to calculate the sum of 2 random numbers rolled on a dice 36000 times. These numbers should range from 1 to 6 in order to simulate the rollin ...

Reorganizing an array while initializing it in Javascript

Upon further review of responses, I have decided to exclude single characters, code, and special characters from the initial creation of the words array. Utilizing the script found at THIS PAGE and executing it in the console on any website, we obtain an ...

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Calculating the size of an array using the begin() and end() functions in C++11 based on the parameter passed

Currently, I am immersing myself in the world of C++ after having experience with Java and JavaScript. One thing that has puzzled me is the inability to pass an array as an argument in C++ like you can in Java. Instead, you must pass a pointer to the first ...

Learn how to show image information in a separate div by clicking on the image using jQuery

Is there a way to show or hide information of an image in a separate div by clicking on the image itself? $(document).ready(function () { $(".cell").click(function () { $(this).find("span").toggle("slow"); }) }); <div class="cell"> ...

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...

In Vue(tify), transitions require children to have keys, but in this case, there are no tags present as children

Trying to implement a transition on a list using Vue and Vuetify, but encountering the error message vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <v-card> I attempted the Vuetify approach <v-fade-transi ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

"Unleashing the Power of AngularJS: Implementing a Global Error Handler to Display and

When building my website, I have multiple Angular apps that require a global error handler to track and display alerts for errors with codes like 500 and 401. Here is what I have so far: In order to create a global error handler module, I've set up t ...

Using the keyboard to access the close button is not an option for me

Despite adding tabindex=0 to the close image button with <img src= "close img link" tabindex="0" alt= "close" title="close" aria-labelledby="close" />, I am unable to use the keyboard to access the bu ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

Retrieve a JSON WebMap using an ArcGIS JavaScript API Map object

Is there a way to retrieve a JSON representation of a WebMap object from a JavaScript Map object in the ArcGIS JavaScript API without relying on ArcGIS.com? It would be ideal if there was a method similar to: webMapAsJSON = map.toWebMap(); The "Export We ...

An effective method for linking a value from one ng-model to another is by identifying and matching a specific string

I have been tasked with binding a value to one model based on the content of another model when it contains a string that starts with "https". For instance, there are two text fields each associated with a different model. <input type="text" ng-model= ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...