Diversifying collection of entities

Imagine having an array structured like this:

[
    {
        id: 1,
        name: "Foo",
        quantity: 2
    },
    {
        id: 2,
        name: "Bar",
        quantity: 3
    },
]

The goal is to duplicate or expand the array elements based on the quantity value. The expected output should look like this:

[
    {
        id: 1,
        name: "Foo"
    },
    {
        id: 1,
        name: "Foo"
    },
    {
        id: 2,
        name: "Bar"
    },
    {
        id: 2,
        name: "Bar"
    },
    {
        id: 2,
        name: "Bar"
    }
]

Is it possible to achieve this outcome without resorting to a loop (for, forEach, etc..)? Can the native methods of the Array object be utilized?

Update:

In case anyone finds it useful, here is a loop-based solution.

const arrayOfObjects = [
    {
        id: 1,
        name: "Foo",
        quantity: 2
    },
    {
        id: 2,
        name: "Bar",
        quantity: 3
    },
];
let result = [];

arrayOfObjects.forEach(element => {
    for (let i = 0; i < element.quantity; i++) {
        const {
            quantity,
            ...newElement
        } = element;

        result.push(newElement);
    }
});

Answer №1

My approach involves utilizing a loop instead of relying on the built-in methods of the Array object, following the suggestion in the comments that a simple loop can be more efficient.

const arrayOfObjects = [
    {
        id: 1,
        name: "Foo",
        quantity: 2
    },
    {
        id: 2,
        name: "Bar",
        quantity: 3
    },
];
let result = [];

arrayOfObjects.forEach(element => {
    for (let i = 0; i < element.quantity; i++) {
        const {
            quantity,
            ...newElement
        } = element;

        result.push(newElement);
    }
});

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

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...

The jQuery draggable feature ceases to function after it has been dropped

I have a scenario with two divs, each housing a list of quantities and items. These items are draggable, and the div containing them is droppable. The condition here is if an item with the same name exists in the div, it cannot be dropped on that div again ...

The function Map() in React-Leaflet cannot be executed, despite the presence of data

I am attempting to replicate the React-Leaflet example of a list of markers. I have an array of objects that I am passing to MarkerList to be transformed into Fragments and displayed on the map. However, my mapping function is not functioning as expected ...

WordPress AJAX call results in a response code of zero

TL;DR: Unique - Go straight to code below for issue. You can view the demo I am working on by following this link. In my `functions.php` file, I first localize my script: function ajaxurl(){ wp_enqueue_script( 'product-selector', get_templ ...

Using ES6 syntax to inject modules into an extended controller can result in the Unknown provider error

Currently, I am facing an issue with creating a child class ModalCtrlChild extends ModalCtrl from my controller class ModalCtrl. Whenever I attempt to do this, I encounter an unknown provider error related to the modules injected in ModalCtrl. The project ...

Utilizing the datepicker options function within a different function

I'm working on a function that utilizes a promise to retrieve data from an asynchronous ajax call: $("#mySelect").on('change', function() { var mySelectValue = $('#mySelect').val(); var promise = getAvailableDates(mySe ...

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

Try rotating a triangle in 3D using either CSS or JavaScript

I want to create a right-angle triangle that looks like this . . . . . . . . . . . . . . . . . . but I also want to add a 3D animation that will transform it into a right angle like this . . . . . ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Show the elements of an array (that have been read and processed from a text file) on separate lines using JavaScript

Hello, I have the code below where a user can upload a text file. I attempted to display the output in a div after splitting it using the @ character. The array elements stored in variables are correctly displayed with new lines in an alert, but they are p ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

Sending vast amounts of string data from one Activity to another

I'm facing a challenge trying to transfer a hefty string-array, possibly 2 or 3 MB in size, to another activity. However, the chunk is failing to pass and all I can see in the logcat regarding the issue is ... !!! FAILED BINDER TRANSACTION !!! To wo ...

Tips for replacing spaces with &nbsp; in a string using ReactJS and displaying it in HTML

<div className="mt-2 font-sidebar capitalize"> {item.title} </div> item.title can vary and be any string retrieved from the backend, such as "all products", "most liked", "featured items", etc. I am looking for a solution to subst ...

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

Validation of form fields appears to be disregarded

I seem to have overlooked a simple issue with this form field validation method. It has worked effectively for me in the past, but now, despite checking all file paths, every time I submit the form, it sends an email regardless of the field content. You c ...

Leveraging promises in conjunction with mongoose operations

I'm new to using promises in conjunction with mongoose query functions such as find() and findById(). While everything seems to be functioning correctly, I am unsure if the way I am chaining then is the proper approach. The goal of utilizing promises ...

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...