Steps to replicate the items in an array

Suppose we have an array :

var array_1 = ['c','b','a'];

What would be the most efficient method to convert array_1 into

['c','c','b','b','a','a'];

or possibly

['c','c','c','b','b','b','a','a','a'];

Answer №1

One approach is to utilize flatMap along with fill in the following way:

function replicate(arr, count) {
  return arr.flatMap(num => Array(count).fill(num))
}

console.log(JSON.stringify(replicate([1,2,3], 2)))
console.log(JSON.stringify(replicate([1,2,3], 3)))

Answer №2

Utilizing the brand new .flat() method allows you to condense an array into a single dimension and multiply the elements by mapping each element to an array containing those elements individually.

var arr1 = ['c', 'b', 'a'];

var arr2 = arr1.map(e => ([e, e, e])).flat();

console.log(arr2);

Answer №3

When iterating over an array and performing additive operations, the choice of method often boils down to personal style. One common approach is using the Array.reduce method...

const arr1 = ['x', 'y', 'z']
const arr2 = arr1.reduce((accumulator, currentValue) => [...accumulator, currentValue, currentValue, currentValue], [])

Alternative methods like map or forEach could also achieve similar results.

Answer №4

To duplicate a character in an array, loop through the initial array and use the Array(x).fill(c) method for each character. Here, x represents the number of duplicates and c is the character you want to replicate. Finally, combine all the new arrays into one unified array.

Answer №5

Utilizing a basic forEach and for loop.

To create multiple duplicates of your array, you can use a function that takes in your array and the desired number of duplications.

const myArray = ['c', 'b', 'a'];

const resultArr1 = makeDuplicates(myArray, 2);
console.log(resultArr1);

const resultArr2 = makeDuplicates(myArray, 3);
console.log(resultArr2);

function makeDuplicates(arr, times) {
  let duplicatedArray = [];
  arr.forEach(item => {
    for(i=0; i < times; i++) {
      duplicatedArray.push(item);
    }
  });
  return duplicatedArray;
}

Answer №6

public static char[] replicateArray(char arr[], int numberOfCopies) {
    char newArr[] = new char[((arr.length) * numberOfCopies)];
    char temp;

    int p = 0;
    for (int k = 0; k < arr.length; k++) {
        for (int i = p; i < newArr.length; i++) {

            for (int j = 0; j < numberOfCopies; j++) {
                newArr[i + j] = arr[k];

            }
            p = i + numberOfCopies;
            break;

        }
    }
    return newArr;

    }

Answer №7

let sampleArray = ['a','b','c'];   
/* If the array contains numbers, you can change elements and handle duplicacy like this - sampleArray = [1,2,3] */

getModifiedResult = (inputArray, duplicacyNumber) => {
    return  duplicacyNumber <= 0 ? inputArray : inputArray.reduce((current, accumulator) =>{
        let arr1 = Array(duplicacyNumber).fill(current);
        let arr2 = Array(duplicacyNumber).fill(accumulator);

        arr1 = isNaN(current) ? arr1   : arr1.map(Number);
        arr2 = isNaN(accumulator) ?  arr2 : arr2.map(Number);

        return (Array.isArray(current) ? current : arr1 ).concat(arr2)
    })
}

console.log( getModifiedResult(sampleArray, 5) )

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

Is there a way to retrieve the text from THREE.TextGeometry?

I recently generated a new Mesh using TextGeometry and added it to an array of meshes: var text3d = new THREE.TextGeometry( "Hello!", { font: "Helvetica" }); text3d.computeBoundingBox(); var textMaterial = new THREE.MeshBasicMaterial({ color: 0xb0bca7 ...

Experiencing difficulty with transferring data from HTML to the backend and then from the backend to another HTML page. Utilizing Google Apps Script

When a click event occurs on my main.html page, I am able to retrieve the ID using the following code: elements.table.on("rowClick", function(e, row){ //e - the click event object //row - row component const ID = row._row.data.ID; google.sc ...

Tips for utilizing the window object in Angular 7

To implement the scrollTo() function of the window object directly, we can use window.scrollTo(0,0). However, when researching how to do this in Angular, I found that many people create a provider as shown below: import {InjectionToken, FactoryProvider} f ...

Script and Ajax loading repeatedly, causing multiple instances of script and Ajax loading

I recently encountered some unexpected issues while debugging and playing around with the code on my website, . Let me walk you through the scenario to understand the problem better. When you click on the "art" tab, two logs appear in the console - one sho ...

What steps are involved in compiling a library without using Ivy?

After compiling my library, I navigated to dist/my-library and encountered the following error message: ERROR: Attempting to publish a package compiled with Ivy, which is not permissible. Prior to publishing, delete and re-build the package without us ...

Create a variable to store the sum value when iterating through a range using jQuery's

Currently, I am in the process of developing a specialized calculator that requires me to calculate the sum of variables within my jQuery.each loop for a specific range from 0 to 4 (equivalent to 5 years). While I have come across several informative reso ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...

ensure that angular's ng-if directive sets aside space to display content when triggered by an event

I'm facing an issue with my modal form setup where if a text-field is left blank, a label saying "it is required" is generated below the field, causing the "Proceed" button to move (along with all other elements below it). How can I make sure that DOM ...

Utilizing Vue to bind data for asynchronous Axios requests

Having an issue with my Vue function that is triggered by a button click. It makes an axios call, but the problem is that no matter what I type in the textarea (v-model taskCommentBody), it sends the data commentBody as blank. Not sure what's causing ...

An unexpected error occurred in Nest.js: No repository was found for the entity "Product"

I have been attempting to register and migrate a new entity in Nest.js, but I keep encountering an error message that says the following: ERROR [ExceptionHandler] No repository for "Product" was found. It seems like this entity is not registered in the cur ...

Base64 versus UTF-8 charset: What sets them apart?

While working with binary files, I discovered that: If it's a text-based file, I need to use data:text/plain;charset=utf-8, and if it's a multimedia file, I should use data:image/png;base64, I attempted to use base64 encoding and encountered a ...

The functionality of right-clicking or context clicking in Internet Explorer 11 using Selenium WebDriver is experiencing issues

When attempting to open/select a context menu by right-clicking on an element on a page, I am encountering an issue. Despite using the Action class to execute the click operation, the contextClick() command seems to be performed at a different location on ...

I always make sure to check for the loading indicator before accessing my partial view

this is the HTML code that I have written. <input type="button" name="signup_submit" data-toggle="collapse" data-target="#panel" onclick="generate('#report', '_DailyReport', 'Reports');" class="btn btn-primary toggle" id=" ...

Retrieve the value of the callback function from outside the callback function (ajax)

My dilemma involves returning a callback value outside of the callback function. Here's an example: I created this function based on the topic discussed in: How do I return the response from an asynchronous call? (function (){ return getAjaxRes ...

The sluggish loading of MVC views through AJAX

I'm currently working on implementing an AJAX call in an MVC View to populate an empty tag using jQuery. Here's the code I'm using: function AjaxLoadPanel(url, id) { var a = 1; $.ajax({ url: url, cache: true, ...

Waiting for response in AngularJS Controller and setting callback

I have developed an AngularJS application with controllers.js and factories.js that I am excited about. However, I am facing a challenge when trying to manipulate the values within the controller (retrieved from the factories). The issue is that these val ...

The attempt to generate a .zip file using Node.js with Egg framework was unsuccessful

I developed a Node.js service using Egg framework to send a local .zip file (compressed directory) to the browser, but encountered an issue. Below is the code snippet: Egg.js // Code for zipping files async download() { const ctx = this.ctx; co ...

Prevent the onClick function of the outer div from being triggered by clicking on the inner div

Similar Question: Stop parent container click event from firing when hyperlink clicked My issue is <div onClick="someJScode();"> ... <div></div> ... </div> I need to prevent someJScode() from executing when the inner di ...

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

Pattern Matching: Identifying partial or complete text

Currently, I'm facing challenges with a small script that is designed to compare the value from a text input with items in an array either partially or completely. I am struggling specifically with the regular expression and its syntax. I was hoping ...