What is the best way to combine TypedArrays in JavaScript?

Looking to combine multiple arraybuffers into a Blob, but facing limitations with TypedArrays that lack handy methods like "push".

For example:

var x = new Int8Array( [ 1, 2, 3 ] );
var y = new Int8Array( [ 4, 5, 6 ] );

The desired outcome is to have [ 1, 2, 3, 4, 5, 6 ].

Answer №1

To achieve this, you can utilize the set method. However, it's essential to keep in mind that this approach will require twice the amount of memory!

var x = new Int8Array( [ 1, 2, 3 ] );
var y = new Int8Array( [ 4, 5, 6 ] );

var z = new Int8Array(x.length + y.length);
z.set(x);
z.set(y, x.length);

console.log(x);
console.log(y);
console.log(z);

Answer №2

To achieve a client-side ~okay solution, you can use the following code:

const x = new Int8Array( [ 1, 2, 3 ] )
const y = new Int8Array( [ 4, 5, 6 ] )
const z = Int8Array.from([...x, ...y])

Answer №3

I frequently utilize the mergeTypedArrays function for combining typed arrays:

function mergeTypedArrays(a, b) {
    // Verify both arrays have truthy values
    if(!a && !b) throw 'Please provide valid arguments for parameters a and b.';  

    // Check for truthy values or empty arrays to avoid unnecessary array construction
    if(!b || b.length === 0) return a;
    if(!a || a.length === 0) return b;

    // Ensure both typed arrays are of the same type
    if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b))
        throw 'The types of parameters a and b do not match.';

    var c = new a.constructor(a.length + b.length);
    c.set(a);
    c.set(b, a.length);

    return c;
}

An unaltered version of the function without null or type checks is as follows:

function mergeTypedArraysUnsafe(a, b) {
    var c = new a.constructor(a.length + b.length);
    c.set(a);
    c.set(b, a.length);

    return c;
}

Answer №4

Suppose I have an array of typed arrays

arr = [ ta1, ta2,..... ta100]

I aim to concatenate all subarrays from 1 to 100 into a single 'finalResult' this particular function does the job for me.

  single_result_array = mergeArrays(arr)


function mergeArrays(arr) {
  // calculating total length of individual arrays
  let totalLen = arr.reduce((acc, value) => acc + value.length, 0);

  if (!arr.length) return null;

   let finalResult = new Uint8Array(totalLen);

      // copying each array over to the final result one after another
      let len = 0;
      for(let ar of arr) {
            finalResult.set(ar, len);
            len += ar.length;
      }

      return finalResult;
   }

Answer №5

Here is a concise code snippet that can merge multiple arrays with mixed types into a single Int8Array:

let mergedArray = Int8Array.from(Array.prototype.concat(...myArrays.map(array => Array.from(array))));

Answer №6

function mergeArrayBuffers (views: ArrayBufferView[]) {
    let totalLength = 0
    for (const view of views)
        totalLength += view.byteLength
        
    let buffer = new Uint8Array(totalLength)
    let position = 0
    for (const view of views) {
        const uInt8View = new Uint8Array(view.buffer, view.byteOffset, view.byteLength)
        buffer.set(uInt8View, position)
        position += uInt8View.byteLength
    }
    
    return buffer
}

Answer №7

If you're a fan of concise code snippets:

  let data = [
    new Uint8Array([1, 2, 3]),
    new Int16Array([4, 5, 6]),
    new Int32Array([7, 8, 9])
  ];

  const mergedUint8Array = new Uint8Array(data.map(array => [...new Uint8Array(array.buffer)]).flat());

Answer №8

Although I appreciate @prinzhorn's solution, I was looking for a more versatile and concise approach:

let arrayA = new Uint8Array([1, 2, 3]);
let arrayB = new Float32Array([4.5, 5.5, 6.5]);

const mergeArrays = (typedArrays, type = Uint8Array) => {
  const result = new (type)(typedArrays.reduce((acc, arr) => acc + arr.byteLength, 0));
  let offset = 0;
  typedArrays.forEach((arr, index) => {
    result.set(arr, offset);
    offset += arr.byteLength;
  });
  return result;
}

mergeArrays([arrayA, arrayB], Float32Array)

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

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

Is there a way for me to compare a string A1 with a value A2 located in index 0 within an array of values?

In my current task, I am attempting to compare two sets of strings: A1 must match A2 when selected. However, if A1 is chosen along with B1, C1, or D1, the comparison should return false. Similarly, selecting B1 should result in a match with only B2, while ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...

The object for checking Ajax connections is not providing any values

I've been working on creating a unique AJAX connection check object, but unfortunately I'm struggling to get it to function properly. :/ Here's the object structure: function Connection(data){ this.isConnected = false, this.check = funct ...

Instructions for including a script and stylesheet exclusively on a single page of a website

I need to incorporate these two lines onto a single page of my website: <script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script> As well as <link href="//cdnjs.cloudflare.com/ajax/libs/OwlCa ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Using Vue.js to dynamically calculate elapsed time

I am attempting to display the changing elapsed time from a specified start time <template> <div class="dashboard-editor-container"> <div class="wrapper__body"> <el-row :gutter="30"> <el-col v-fo ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

vuex: initialize values using asynchronous function

My store setup is as follows: export const store = new Vuex.Store({ state: { someProp: someAsyncFn().then(res => res), ... }, ... }) I'm concerned that someProp might not be waiting for the values to be resolved. Is th ...

Tips for saving data in the $localStorage as an object

I need to store all the items in $localStorage like this: $localStorage.userData.currentUser = data.name; $localStorage.userData.devId= data.id; $localStorage.userData.userRole = data.roles[0].name; $localStorage.userData.userId = data.user_id; Here is t ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

What is the best way to iterate through data with ajax and mysql?

I have a school project where I need to create an MP3 album playlist using a premade PHP API with JavaScript or jQuery (without using PHP). I can input the data via an AJAX call. The goal is to add multiple songs along with their URLs into a column named s ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

JavaScript progress bar with extended duration, inspired by the success-oriented approach

Currently, I am in search of a unique solution or plugin that can replicate the same effect as Kickstarter's crowd fund long term progression bar. It seems like existing solutions only offer short term dynamic progress bars that indicate the percentag ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

List of dropdown options retrieved from SQLite database

I am attempting to retrieve data from an SQLite database table in order to populate a dropdown menu list. My thought process is outlined below. The main issue I am facing is how to integrate the JS function with the HTML section. HTML.html <label ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

Retrieve information from an SQL database using user input in a Classic ASP form without the need to refresh the page

Currently, I am in the process of incorporating a new function into an existing Classic ASP system. This feature involves allowing users to scan a barcode that will automatically populate a text field within a form inside a bootstrap modal. The scanner has ...