Transfer the contents of one array into the center of another array using JavaScript

I have been looking for answers here, but I can only find solutions for different programming languages.

Currently, I am dealing with 2 Uint8 typed arrays.

var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];

My goal is to replace the contents of arr2 with arr1, starting at the 4th position. This means arr2 should look like this:

arr2 = [0,1,2,0,0,0,6,7,8,9];

If I was not trying to do this in the middle of the array, I could easily use set as shown here:

arr2.set(arr1);

This would give me the following result:

arr2 = [0,0,0,4,5,6,7,8,9];

Although I know that looping through arr2 and copying values individually can achieve the desired outcome, it is incredibly slow compared to using set (and performance is crucial because I am copying an entire array of canvas image data 24 times per second).

Is there a function available that can copy into the middle of an array with the same efficiency as set?

Answer №1

Implement the typedarray.set(array[, offset]) method to set values with an offset.

offset Additional Parameter

The designated position in the target array to start writing values from the source array. If not specified, defaults to 0 (meaning overwriting starts at index 0).

const arr1 = new Uint8Array([0,0,0]);
const arr2 = new Uint8Array([0,1,2,3,4,5,6,7,8,9]);

arr2.set(arr1, 4);

console.log(arr2);

Answer №2

To implement this functionality, utilize the slice method along with the spread syntax:

const combineArrays = (sourceArr, index, targetArr) => [
  ...sourceArr.slice(0, index),
  ...targetArr,
  ...sourceArr.slice(index)
]

var array1 = [0,0,0];
var array2 = [0,1,2,3,4,5,6,7,8,9];

const mergedArray = combineArrays(array2, 3, array1);
console.log(mergedArray);

The usage of .slice ensures that the original array remains unaltered as it returns a new shallow copy, unlike splice.

Answer №3

Have you considered utilizing the offset parameter in the set method when working with typed arrays?

arr2.set(arr1, 3)

This will allow you to start overwriting from the 4th element of the target array. More information here.

It appears that this functionality aligns well with your requirements, assuming I've interpreted your question correctly.

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

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05. The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues: The calculated value should be rounded to two decimal points. For ex ...

I encountered a challenge with a cross-site scripting filter that is preventing me from storing a JavaScript variable in a MySQL database using a

I am currently working on a project where I need to save a JavaScript variable into a MySQL database using a Python CGI script. In this case, the JavaScript variable contains the following information: <li style = "width: 300px; background-color: white ...

Issue with executing Mongoose's .save() method

I am facing an issue with a piece of code that is not functioning as expected. My goal is to save a user document after modifying it with an ObjectId by adding it to an array. However, the user.save() function does not seem to execute, as the document rema ...

Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands. Check out a similar question, along with ...

Why isn't my Vue2 data updating in the HTML?

Starting my journey with Vue, I have been finding my way through the documentation and seeking support from the Vue community on Stack Overflow. Slowly but steadily, I am gaining a better understanding of how to create more complex components. The issue I ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Having trouble getting Visual Studio Code to execute my build command in launch.json

Whenever I run this specific command in a command prompt, everything works perfectly: browserify -u jquery /public/index.js -t babelify -o /public/scripts/bundle.js & node /server.js But when attempting to integrate it into the program section of my ...

Unexpected color changes when hovering over sparkline graphs

One of the jquery plugins I'm using is called sparkline Here's an example of how I am using it: $(function(){ $("#sparkline5").sparkline([2, 8, 10, 22], { type: 'pie', height: '140', sliceColors: [ ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Utilize the map function on an array object to present data in a table using React framework

My parent component passes an array object that looks like this: https://i.sstatic.net/Nqh81.png I want to organize these values into a table with the keys in one column and their corresponding values in other columns. The desired format is shown here: ht ...

Creating a boundary: A step-by-step guide

There is an element that I need help with <div id="square"></div> This element has the ability to move around the document var square = document.getElementById("square"); document.body.onkeydown = function(e) { if (e.keyCode == 37) { ...

What steps can be taken to ensure that the array of identifier tags for each student remains intact even after being re-fetched from the API

I am facing an issue where my list of students displayed on the web browser resets when filter fields are cleared. The students are fetched from an API and displayed based on name/tag filters. But, after clearing the filters, the tags associated with each ...

Extracting IDs, classes, and elements from a DOM node and converting it into a string format

Can someone please guide me on how to extract the DOM tree string from an element? Let's consider this HTML structure: <div> <ul id="unordered"> <li class="list item">Some Content</li> </u ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

Python, JavaScript, and Selenium RC all work together within loop statements on .aspx pages

I've been diving into Python on my own for the past few months. My initial project involves creating a browser driver test case with the Selenium RC web driving framework (I'm avoiding importing webdriver to keep things simple). The goal is to ha ...

Issue encountered when initializing Firebase function test

Recently, I've been experimenting with testing my Firebase cloud functions. I meticulously followed the guidelines provided in the documentation, but encountered an unexpected error during the execution of the tests. Despite generating multiple keys a ...

The issue with Internet Explorer failing to adhere to the restrictions set on maximum width and

I'm attempting to scale my images precisely using CSS: HTML: <div id="thumbnail-container"> <img src="sample-pic.jpg"/> </div> CSS: #thumbnail-container img { max-height: 230px; max-width: 200px; } In this scenario, ...

Utilizing JavaScript functions within Django framework

I'm in the process of developing an app using django. My goal is to create a score counter that increases based on the number of people watching through their webcam. After successfully implementing a function to determine the live audience count, I ...