Tips for dividing the rows within an array using the match() function?

Within my matrix are arrays of rows.

let matrix=[['hello'],['world']];

I am looking to duplicate each row within the matrix.

matrix=matrix.map(x=>String(x).repeat(2)).map(x=>x.match(new RegExp??))

The desired outcome should be

[['hello','hello'],['world','world']]

Answer №1

To replicate the arrays, utilize the concat function

const matrix = [
  ['goodbye'],
  ['universe']
];
const result = matrix.map(arr => arr.concat(arr))
console.log(result);

Alternatively, if you have an array of arrays and wish to obtain multiple entries instead of just one:

const matrix = [
  ['goodbye'],
  ['universe']
];
const result = matrix.map(arr => Array(3).fill(...arr));
console.log(result);

Answer №2

Your current code approach will not work for a few reasons. Firstly, there is no method called Array::repeat(). Secondly, it does not make sense to duplicate an array using the RegExp::match() method. Lastly, you are attempting to assign a value to a constant variable which is not allowed. It would be more efficient to use simpler techniques.

If you want to duplicate the original array, you can simply mutate it like this:

const matrix = [
  ['hello'],
  ['world']
];
// Push each array into itself to duplicate
matrix.forEach(arr => arr.push(...arr));
console.log(matrix);

This method is definitely faster than overwriting the array with a new one. You can see the comparison in the image below:

https://i.sstatic.net/qAtnH.png

<script benchmark data-count="5000000">

// @benchmark The fourth bird
{
let matrix = [
  ['hello'],
  ['world']
];
matrix = matrix.map(a => a.concat(a))
}

// @benchmark Alexander
{
const matrix = [
  ['hello'],
  ['world']
];

matrix.forEach(arr => arr.push(...arr));
matrix;
}
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

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

React Array Not Behaving Properly When Checkbox Unchecked and Item Removed

When using my React Table, I encountered an issue with checkboxes. Each time I check a box, I aim to add the corresponding Id to an empty array and remove it when unchecked. However, the current implementation is not functioning as expected. On the first c ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

Tips for implementing the select all feature in mat-checkbox for Angular 5

Here is the code snippet from my HTML template: <mat-card> <mat-card-content> <h2 class="example-h2">Select Employee</h2> <section class="example-section"> <mat-checkbox [(ngModel)]="ch ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Navigating collisions in the ECS architecture: Best practices

I'm currently developing a game using typescript and the ECS design pattern. One of the challenges I'm facing is handling collisions between different entities within the game world. I have an entity called Player which comprises several componen ...

Can Angular i18n facilitate language switching?

My objective is to switch the language from English (United States) to Indonesia using a button. View Source Code https://i.sstatic.net/0YlfWaCY.gif The issue is that the tutorial does not cover how to implement the language change feature. Why opt for ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

What is the best method for fetching data returned by AJAX using PHP?

I have a data structure similar to the one below, which is returned via AJAX to another file: $data = array(); $data['message'] = "You are searching: $domain!"; $data['domain:name'] = "domain.tld"; $data['domain:registrar ...

What is the best way to create a dynamic data structure using an array?

I recently discovered that Vuejs does not track changes in data beyond the first level of an array. Is there a way to modify this behavior? new Vue({ el: '#container', data: { value: [], }, beforeMount() { this.value[0] = &apo ...

Managing MUI form fields using React

It seems like I may be overlooking the obvious, as I haven't come across any other posts addressing the specific issue I'm facing. My goal is to provide an end user with the ability to set a location for an object either by entering information i ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...

The component briefly displays the previous state before updating in the Material-UI Alert component

Whenever there is an error from an API while a user is registering, an alert is displayed on the form page. To handle this, an Alert component was created: <Snackbar open={open} autoHideDuration={9000} onClose={() => { setOpen(f ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

Tips for checking the type radio button input with Angular.js

I want to implement validation for a radio button field using Angular.js. Below is the code snippet I am working with: <form name="myForm" enctype="multipart/form-data" novalidate> <div> <input type="radio" ng-model="new" value="true" ng- ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

Encountering a "Cannot GET /PATH" error while developing a NUXT application due to a DOT present in

In my nuxt application, I encountered a peculiar issue. When I execute npm run dev, everything functions properly. However, after running npm run build and then npm run start, I face the error message stating cannot GET [path of the page here] I noticed t ...

Using innerHTML within a JS function causes the class to malfunction

I want to embed HTML code using innerHTML, which will add an input with the class .flatpickr-date. let newInput = '<input type="text" class="flatpickr-date">' document.getElementById('id').innerHTML = newInput; In my JavaScript ...

Managing integer values in controllers with .NET Core 6

I have a simple API controller where I can manipulate any model in my design, but I'm having trouble handling int or string values. Here's a snippet of my code: [Route("Get"), HttpPost] public async Task<JResultModel> Get(int id) { if ...