Tips for compressing a compressed array

Currently, I am facing a challenge in attempting to flatten a Uint8ClampedArray.

The initial array structure is data = [227, 138, 255…] and after creating an array from that like

enc = [Uint8ClampedArray[900], Uint8ClampedArray[900], Uint8ClampedArray[900]...]
, my goal is to flatten it.

I have tried various methods and solutions, including:

the method suggested by MDN

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);

using concat

data = [].concat.apply([], enc);

and utilizing a function

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

However, none of these approaches have been successful so far. The array keeps returning in its original form. Can anyone provide guidance on the right approach and explain why this is happening?

-EDIT- In essence, I need it to be converted into a regular Array object, similar to the starting one without a specified type.

Answer №1

If the variable enc is an array of Uint8ClampedArray types, you can use this concise statement to flatten it:

var flattened = Uint8ClampedArray.from(enc.reduce((a, b) => [...a, ...b], []));

This code snippet achieves the same result as the following traditional approach:

var flattened = Uint8ClampedArray.from(enc.reduce(function(a, b){
  return Array.from(a).concat(Array.from(b));
}, []));

In response to your query on why the reduce function did not work as expected:

[].concat(Uint8ClampedArray([1, 2, 3, 4]));

Regrettably, this code does not yield [1, 2, 3, 4], instead it produces [Uint8ClampedArray[4]]. Typed Arrays do not play well with the concat method.

Answer №2

To start, I recommend calculating the total length before using the set method. One advantage of using set is

If the source array is a typed array, the two arrays may share the same underlying ArrayBuffer; the browser will intelligently copy the source range of the buffer to the destination range.

function flatten(arrays, TypedArray) {
  var arr = new TypedArray(arrays.reduce((n, a) => n + a.length, 0));
  var i = 0;
  arrays.forEach(a => { arr.set(a,i); i += a.length; });
  return arr;
}
console.log(flatten(
  [new Uint8ClampedArray([1,2,3]), new Uint8ClampedArray([4,5,6])],
  Uint8ClampedArray
));

Another approach is to use blobs, as suggested by guest271314. The correct method would be

function flatten(arrays, TypedArray, callback) {
  var reader = new FileReader();
  reader.onload = () => {
    callback(new TypedArray(reader.result));
  };
  reader.readAsArrayBuffer(new Blob(arrays));
}
flatten(
  [new Uint8ClampedArray([1,2,3]), new Uint8ClampedArray([4,5,6])],
  Uint8ClampedArray,
  result => console.log(result)
);

Answer №3

Upon reviewing the MDN documentation, it is clear that TypedArrays do not have access to several standard JavaScript array functions.

One workaround for this limitation is to gather the values from the clamped array and create a new one using the following method:

var enc = [Uint8ClampedArray.of(1, 2), Uint8ClampedArray.of(4, 8), Uint8ClampedArray.of(16, 32)];

var flattened = Uint8ClampedArray.from(enc.reduce(function(acc, uintc){
  Array.prototype.push.apply(acc, uintc);
  return acc;
}, []));

console.log(flattened); // [object Uint8ClampedArray]
console.log(flattened.join(',')); // "1,2,4,8,16,32"

Answer №4

Revision, Upgraded

firefox, nightly currently gives

[[object Uint8ClampedArray],[object Uint8ClampedArray],[object Uint8ClampedArray]]
when using FileReader() result as highlighted by @Oriol.

An alternative method utilizing spread element, rest element, for..of, which provides identical outcomes to chromium, chrome with the use of Blob(), FileReader(); TextEncoder(), TextDecoder(); JSON.parse() methods

var enc = [new Uint8ClampedArray(900)
            , new Uint8ClampedArray(900)
           , new Uint8ClampedArray(900)];

var res = [];
for (let prop of enc) [...res] = [...res, ...prop];

console.log(res);

or, more concise, as recommended by @Oriol

var res = [];
var enc = [new Uint8ClampedArray(900), new Uint8ClampedArray(900)]; 
for (let prop of enc) res.push(...prop);

You can utilize Blob() to combine parameters into a single Blob object, along with FileReader(), JSON.parse()

var enc = [new Uint8ClampedArray(900)
            , new Uint8ClampedArray(900)
           , new Uint8ClampedArray(900)];

var blob = new Blob([enc]);

var reader = new FileReader();
reader.onload = () => {
  console.log(JSON.parse("[" + reader.result + "]"))
}
reader.readAsText(blob);

Alternatively, using TextEncoder(), TextDecoder(), JSON.parse()

var enc = [new Uint8ClampedArray(900)
            , new Uint8ClampedArray(900)
           , new Uint8ClampedArray(900)];

var encoder = new TextEncoder();
var arr = encoder.encode(enc);
var decoder = new TextDecoder();
var res = JSON.parse("[" + decoder.decode(arr) + "]");
console.log(res);

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

Tips for successfully implementing programmatic routing in Nuxt

In Nuxt, the router is pre-configured for us and we have the ability to use the <NuxtLink to="/about" prefetch>About page</NuxtLink> component. But what is the process for achieving programmatic routing in Nuxt? ...

filter array based on property value

var arr = [ {'a':1,'b':2}, {'a':1,'b':3}, {'a':1,'b':0}, ] I am looking to retrieve an array where the value of property b is 2 ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

What is the best way to have a TypeScript function return a class?

Currently, I am utilizing TypeScript alongside a dependency injection library that functions quite similarly to Angular 1 - essentially, you register a factory with your dependencies as arguments. Here is an example of how I would register a class using E ...

Create a PHP array from a MySQL database using the "id" column as the key value pairs

My MySQL database structure is as follows: ID TEXT PARENTID 20 Item1 null 23 Item2 20 27 Item3 20 80 Item4 27 I am aiming to retrieve this data in an array format like so: Array ( [2 ...

Reveal unseen information on the webpage upon clicking a link

I have successfully implemented a fixed header and footer on my webpage. The goal is to make it so that when a user clicks on a link in either the header or footer, the content of that page should appear dynamically. While I have explored various styles, ...

Tips for effectively showcasing the counter outcome amidst the increase and decrease buttons

Currently, I am in the process of learning Angular and have created a component called quantity-component. Within the quantity-component.component.html file, I have implemented 2 buttons for increment (denoted by +) and decrement (denoted by -). The decrem ...

Is there a way to automatically activate a navbar item without the user having to click on a navigation link first?

I'm currently working on a website and I've configured the navigation items so that when you click on a nav-link, it changes the active class to the clicked link. However, I'm wondering how I can set a specific link to be active by default ...

Is it better to use a canvas for a more efficient animation when changing the background image on pagescroll?

I'm currently working on a parallax website that consists of a sequence of around 400 images. The background images change dynamically as the user scrolls through the page, creating a smooth animation effect. While I have managed to implement the scro ...

Spotlight the flaw in the card's backbone using JS

What's the most effective method for emphasizing an error card view in backbone? Initially, I render 10 cards as UI where users input details in each card. Upon clicking submit, I validate all the details by parsing through collection->models. Curr ...

If the value is empty, opt for a different image within the array

I am currently dealing with an array of objects that contain both an ImageUrl and a ThumbUrl. If the ThumbUrl is null, I want it to be replaced with the ImageUrl. I have attempted a solution, but it is not functioning properly: $.each(results.Photos, fu ...

Strategies for detecting file import failures within Angular UI Grid

Currently implementing Angular UI Grid for file imports. Here is my configuration: enableGridMenu: true, importerDataAddCallback: function (grid, newObjects) { Encountering an error when trying to import non-CSV files: uncaught exception: UNEXPECT ...

What could be causing the array index to fall outside the bounds in this particular algorithm?

Currently, I am practicing a code that is fairly self-explanatory, as shown in the commented section below. using System; using System.Collections.Generic; using System.Linq; public class Program { public static int[,] GetPairs ( int [] arr ) { ...

not getting any notifications from PHP

Despite receiving a status of '1' from this process file, my JavaScript code seems to be working fine. However, I am facing an issue with not receiving the email. <?php //Retrieve form data. //GET - user submitted data using AJAX //POST - in ...

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

Mongoose currency does not display fractional values

Struggling to implement a Schema with a 'price' field using Mongoose currency by following the guidance in the documentation. However, the output is displaying prices without two decimals (e.g., 499 instead of 4.99). Surprisingly, when I use cons ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Attaching data to Vue model on the fly within a component

Currently, I am working on creating a straightforward form that will allow users to input various types of currency. Below is a link to a fiddle that demonstrates what I am aiming for, although it is not functioning as intended at the moment: https://jsfi ...

PHP - Validating the elements within an array

I have a specific task at hand. I need to compare a user name and password in each element of an array to find a match with an existing user. There are two arrays involved - one containing all the user information and another containing the login attempts ...

Choosing the subsequent element that comes before

<tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> <tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> &l ...