Quickest method for duplicating an array in Javascript

I've been exploring efficient methods for creating an array by repeating an element a specified number of times. In my case, the repeated element is usually another array, resulting in a long 2-dimensional array. Speed is crucial for my task, and I'm on the lookout for the fastest solution. It's worth mentioning that in each example, c=[element] since that's how it appears naturally in my code.

After some research, I've identified a few options. The most basic one is option 1:

function repeatSimple(c, n) {
  var arr = [];
  for (var i=0; i<n; i++) {
    arr = arr.concat(c);
  };
  return arr;
};

Another alternative was suggested by gdbdmdb in response to a similar question (Concatenate array to itself in order to duplicate it):

function repeatApply(c, n) {
  return [].concat.apply([], Array.apply(0, Array(n)).map(function() { return c }));
};

Although these are viable options, I had reservations about both approaches. The first option involves calling concat multiple times, while the second option seemed complex. Consequently, I devised one more method:

function repeatBinary(c, n) {
  var arr = [];
  var r = 0;
  while (n>0) {
    r = n%2;
    if (r>0) {
      arr = arr.concat(c);
    };
    n = (n-r)/2;
    if (n>0) {
      c = c.concat(c);
    };
  };
  return arr
};

This approach minimizes the number of concat calls to at most 2log_2(n) times.

Hence, my query remains: Which method offers the quickest way to achieve this task? Are the options I've presented here optimal, or is there a faster solution available? Do all these methods perform similarly in terms of speed, making the choice insignificant?

Answer №1

If you want to achieve this task quickly without using the concat function, try the following approach:

function repeatSimple(element, times)
{
    var result = [];
    for(var i=0;i<times;i++)
      result.push(element);
    return result;
}

Alternatively, if you prefer not to utilize the push function, you can directly assign values to array elements like so:

function repeatSimple(element, times)
{
    var result = Array(times);
    for(var i=0;i<times;i++)
      result[i] = element;
    return result;
}

Another clever method involves joining an array and then splitting it, as shown here:

function repeatSimple(element, times)
{
    (result = Array(times).join("," + element).split(',')).shift()
    return result;
}

Keep in mind that the last function returns an array of strings, requiring conversion of each element to the desired type. Regardless, these functions offer helpful solutions.

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

PHP - Eliminate elements from an array based on a specified parameter

After searching for similar questions, I couldn't find a solution that fits my current PHP skills. My query seems simple enough to be resolved with just a few lines of code, based on the solutions I came across. So, here's my question! The code ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

leveraging angular service with ionic framework

(function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$http']; function UserService($http) { var service = {}; ...

Creating a dynamic slide JavaScript carousel

I am in search of a JavaScript library that can help me create a slider similar to AnythingSlider or . The key feature I am looking for is the ability to dynamically add new slides and seamlessly transition to them. It is also important that the slider all ...

Tips on how to make content slide upwards

Need help with sliding menus? I have a solution for you. One issue is that the top menu option slides down instead of up. Let's fix it. Menu Code: <div class="additional-navigation-wrapper"> <div class="additional-navigation"> ...

Divider displayed between images in Internet Explorer 8

On my website, I have arranged four images in a square using the code below: <div id="tempo_main"> <div id="tempo_content"> <div style="text-align: center;z-index: 3;position: absolute;right:350px; left:350px; t ...

Issue with displaying image element over another element

I recently encountered a unique challenge with my SVG element, which acts as a container for a chessboard I developed. In certain key moments of the game, such as when a pawn is promoted and a player needs to choose a new piece, I found it necessary to hav ...

Build an intricate nested array structure using the properties of an object

My data object is structured like this: "parameters": { "firstName": "Alexa", "lastName": "Simpson", "city": "London" } The task at hand involves implementing the followin ...

PhantomJS encountered an issue: Attempting to access the 'write' member of a deleted QObject is not allowed

I am in the process of creating a web API on port 7788 that will accept JSON data. This JSON data will then be passed to my API which will render a website. Next, PhantomJS will search for an element on that page and the web API on port 7788 should return ...

What is the most effective method for transforming a space-separated list of classes into a jQuery selector?

Is there a quick and efficient method for converting a space-separated list of classes like: classOne classTwo classThree into a selector such as: $('.classOne .classTwo .classThree') I am considering utilizing either a loop to construct a se ...

Troubleshooting Issue with Bootstrap 4 Modal Varying Content Display

Dealing with a minor issue where I'm unable to get a modal to fetch data from an HTML table and populate it into a Bootstrap 4 Modal. I've attempted various methods as evident in the code snippets below. Currently in a learning phase, I need to ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

In JavaScript, the function yields a proxy rather than an object

Let's say I have an array: const arr = ['one', 'two', 'three'] Now, imagine I have a function that is designed to take an array of strings and return an array of objects: const func = (arr) => arr.map(item => ({str ...

Unusual Array Glitch

After running this code in Java, I encountered an "ArrayIndexOutOfBoundsException: 215737344" error. However, the S.O.P statements are printing "215737344". I'm confused as to why the loops are continuing instead of stopping when they should. public ...

Can you explain the meaning of "char *argv[]"?

In my program, I have the following code snippet: #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i=0; i < argc;i++) { printf("argv[%d] = %s\n", i, argv[i]); } } I am puzzled by the argumen ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Switching React Icons when Clicked

I'm struggling to understand this. I want the React icons below to be filled and remain filled when clicked, changing back to outlined when another is clicked. Here's the code: import { useState } from "react"; import { Link } from "react-router- ...

issues encountered when trying to integrate bootstrap.js in Django framework

My website is built using the Django templating engine with Bootstrap for design and basic JavaScript. While the CSS components from Bootstrap are working fine, I'm having trouble getting the JavaScript to work: {% load staticfiles %} <!d ...