Replicate the array multiple times and combine them into a single flat array

I have a four-element array that I need to copy to another array four times. I achieved this by concatenating the array four times.

Here is what I tried:

let demoProperties = []
  .concat(fourDemoProperties)
  .concat(fourDemoProperties)
  .concat(fourDemoProperties)
  .concat(fourDemoProperties);

I also attempted another approach using map and reduce, but it required iterating twice.

If anyone knows of a simpler or more efficient way to copy an array N times, I would greatly appreciate any suggestions you may have.

Answer №1

If you want to duplicate an array in JavaScript, there are a few methods you can use:

const originalArray = [1, 2, 3, 4];
const duplicatedArray = [...originalArray, ...originalArray];

You can also achieve the same result using Array#fill in combination with spread syntax:

const originalArray = [1, 2, 3, 4];
const duplicatedArray = [].concat(...Array(2).fill(originalArray));

console.log(duplicatedArray);

Note: It's important to understand that these methods create shallow clones. If your array contains objects, changing one object in the duplicated array will affect all "copies". See this example below:

const originalArray = [{ x: 100 }, { y: 200 }];
const duplicatedArray = [...originalArray, ...originalArray];

duplicatedArray[0].x = 500;

console.log(duplicatedArray);

Answer №2

Depending on whether you want to maintain the reference among the sub arrays or not, the way you go about it can vary.

var ar  = [1,2,3,4],
    ars = Array.from({length:4}).map(_ => ar),
    brs = Array.from({length:4}).map(_ => ar.slice());
console.log(ars);
console.log(brs);

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

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

Experience the seamless transition of new CSS animations

I designed a basic HTML game where a moving box disappears when clicked on. However, the animation that follows does not originate from the click location but rather from the original position. I believe the remove @keyframes at 0% should be based on the ...

What is the process of directing a data stream into a function that is stored as a constant?

In the scenario I'm facing, the example provided by Google is functional but it relies on using pipe. My particular situation involves listening to a websocket that transmits packets every 20ms. However, after conducting some research, I have not foun ...

Scrolling to top using jQuery - Problem with incorrect anchor

I am attempting to implement a scrollTop animation that scrolls to an anchor within a fullscreen <section>. However, the issue is that it does not scroll to the correct anchor on the first click. Below is the code snippet. <nav id="scroller"> ...

Sharing Data via JSON for a Pop-Up Display

section of a website, there is a button that, when clicked, triggers a small pop-up. The data being posted appears to be in JSON format as seen in HttpFox. Personally, I have little knowledge of javascript and AJAX. When the specific button is clicked, i ...

Transfer content within <pre> tags to the clipboard using a Vue.js application

I am currently developing a Chrome extension using Vue.js where I aim to copy the content within a pre tag section to the clipboard with the click of a button. By assigning an element ID to the pre tag, I can retrieve the content using a copyToClipboard() ...

The onclick functionality is not functioning properly within email communications

My JavaScript code contains an AJAX call within Datatables, and this snippet of code is causing an issue: { "data": null, "width": "10%", "render": function(data){ icon2 = '<center><button type="button" class="btn btn-info ...

`How can I extract information from the internet?`

I am attempting to retrieve data from the following URL: . My focus is on obtaining the raw data series rather than the data presented in tables and charts. Although the website provides a button for downloading a .csv file, I am unsure of how to automat ...

Attempting to establish a means to switch between languages

Currently, I am in the process of implementing a language switch feature for a website project that I am currently working on. This feature will allow users to seamlessly switch between English, Latvian, and Norwegian languages. To achieve this functionali ...

Access a designated tab within a CSS-designed tab system

Can anyone offer some assistance? I currently have a tab structure created using CSS. The first tab is set as the default when the page loads. I am looking to create a link from another page that will take users directly to the page with the tabs and ope ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Experiencing a disappearing session on Express.js happens approximately every 3 minutes (I can relate to this problem as

I am encountering a similar issue to the question mentioned here: Express.js session lost after about 3 minutes Unfortunately, I have not been able to find a solution yet. This is my Session Code: app.use( session({ secret: 'secret', resave ...

What is the simplest method to check for the presence of a value within an object when utilizing lodash or angularjs?

I'm encountering an issue where this code works perfectly if "obj" is a collection, but falls short when trying to determine if a value exists within a single object. What would be the most efficient approach, utilizing either lodash or AngularJS, to ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

What is the best way to identify the largest sublist within an array?

Is there a way to determine the largest sublist given this scenario? Imagine having a collection of n pixel RGB values: For example, when n = 3, pixel[1]: 255, 255, 255 pixel[2]: 0, 20, 0 pixel[3]: 5, 13, 63 The goal is to identify the largest sublist ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Arranging JSON based on values in an array using node.js

Seeking assistance with sorting a JSON object by specific keys within a node.js program. The task involves arranging the object in ascending order based on the "trip_miles" value when the "trip_name" equals CC, and then extracting only the id's as out ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...

Tips on dividing a div into two separate pages when converting to PDF

I am working on an asp.net MVC project and I need to convert a HTML div into a PDF with two separate pages. Here is an example of my code: HTML Code <div class="row" id="mycanvas"> <p>This is the first part of my content.</p> <p ...

Error Connecting to Database with Node.JS MySQL Module - ECONNRESET Issue

Attempting to establish a connection with my database using the mysql module has been quite the challenge. Each time I try, an error seems to pop up: read eCONNRESET There is problem. (The final part is from my console log, as seen below.) I've ruled ...