Copy the contents of matrixA into matrixB and append a new element to each array within matrixB

I want to copy the values from matrixA into matrixB and then add a new element to each array in matrixB.

let number = 100;

matrixA = [
    [1, 2],
    [3, 4]
];
matrixB = [
    [1, 2, 100],
    [3, 4, 100]
];

Currently, my code looks like this:

for (let n in matrixB){
    matrixB[n] = matrixA.slice();
}

However, I am encountering difficulties in adding the "number = 100"

Answer №1

Kindly refer to the code snippet provided below for implementation.

const matrixA = [
    [1, 2],
    [3, 4]
];
const number = 100;
const matrixB = matrixA.map(arr => [...arr, number]);
console.log(matrixB);

Answer №2

Here are a couple of ways to achieve the desired result:

console.time('example');
const array1 = [[1, 2], [3, 4]], array2 = [];
for(let arr of array1){
  array2.push([...arr, 100]);
}
console.log(array1); console.log(array2); console.timeEnd('example');

Another approach would be:

console.time('example');
const array1 = [[1, 2], [3, 4]], array2 = array1.map(arr=>[...arr, 100]);
console.log(array1); console.log(array2); console.timeEnd('example');

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

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

I am seeking to retrieve data from MongoDB by utilizing the limit feature, while also sending a specific query

I'm currently facing some confusion with the limit functionality in MongoDB. I want my code to specifically retrieve data for just two hotels by sending a query request from the backend. export const getHotels = async (req, res, next) => { try ...

When utilizing the ::first-letter pseudo-element on <sub> and <sup> tags

Why is the <sub> and <sup> not supporting the ::first-letter CSS pseudo-element? Any solutions? p:first-letter, sub:first-letter, sup:first-letter { color: red; font-weight: bold; } <p>This text contains <sub>subscript</su ...

How can one restrict the display of fields in the Meteor aldeed tabular package?

How can I restrict certain data from being displayed in an aldeed tabular datatable? For instance, if my collection includes attributes A, B, C, D and attribute C contains sensitive information that should not be published, is there a way to prevent it fro ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

When using React.js, clicking on an answer option will change the color of all options, not just the one that was clicked

I'm currently working on my quiz page where all answer options change color when clicked. However, I only want the selected answer option to be colored based on its correctness. The data is being retrieved from a data.json array. export default functi ...

Unable to retrieve element using getElementById with dynamically assigned id

After researching on Google and browsing through various Stack Overflow questions (such as this & this), I have not been able to find a solution. I am currently working on validating dynamically generated rows in a table. The loop and alert functions a ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Removing the hash symbol in Angular: A step-by-step guide

My experience with AngularJS is new, and I am currently working on removing the # from the URLs without utilizing NODE or Express. The project is being hosted locally on MAMP, with index.html acting as the main entry point. Within the structure, there are ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Displaying a project in the same location using jQuery

Struggling with jQuery and positioning hidden items that need to be shown? I have two white boxes - the left one is the Client Box (with different names) and the right one is the Project Box (with different projects). My goal is to show the projects of a c ...

Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help. // CONVERT BINARY TO DECIMAL // (100110)2 > ( ...

Refreshing the Mocha Server

Recently, I encountered a situation where I needed to automate some cleanup tasks in my Express server using Mocha tests. In my server.js file, I included the following code snippet to manage the cleanup operations when the server shuts down gracefully (s ...

What is the secret to the lightning speed at which this tag is being appended to the DOM?

Have a look at this concise sandbox that mirrors the code provided below: import React, { useState, useEffect } from "react"; import "./styles.css"; export default function App() { let [tag, setTag] = useState(null); function chan ...

Identifying errors in a React component upon loading

As I delve into my project, my main focus lies on detecting errors within a component. The ultimate goal is to seamlessly redirect to the home page upon error detection or display an alternate page for redirection. I am seeking a programmatic solution to ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

Using Jquery Chosen Plugin to Dynamically Populate One Chosen Selection Based on Another

Good evening to all, please excuse any errors in my English. I have successfully integrated a jQuery Chosen plugin with my 'estado' field (or province). My goal is to populate another jQuery Chosen plugin with the cities corresponding to that s ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...