Home > Blockchain >  Concatinate different type arrays
Concatinate different type arrays

Time:04-19

suppose, array1 = ['B', 'G', 'R', 'A'], array2 is Uint8Array, how to concatinate these two arrays ?

I used var array3 = array1.concat(array2), but the result seems wrong , and array3.length is alwalys 5, regardless of content of array2.

CodePudding user response:

Your result (array3) must also be a Uint8Array array.

So, in your example the following should achieve what you're looking for:

const array3 = new Uint8Array([ ...array1, ...array2]);

CodePudding user response:

You can do:

var array2 = Array.from(uint8Array);
var array3 = array1.concat(array2);

CodePudding user response:

Your code is creating a new array with your four strings followed by the Uint8Array as a single element.

Array.prototype.concat is an odd beast. If you give it arguments that aren't "concat spreadable" (for instance, things that aren't arrays), it includes those values as simple elements in the array it creates.

Typed arrays are not concat spreadable:

const uint8 = Uint8Array.from([3, 4]);
console.log(uint8[Symbol.isConcatSpreadable]); // undefined (and the default is false)
const softArray = [1, 2];
const result = softArray.concat(uint8);
console.log(result.length); // 3
console.log(result[0]); // 1
console.log(result[1]); // 2
console.log(result[2]); // (A Uint8Array containing 3, 4)

You could use spread instead of concat:

const array1 = ['B',  'G',  'R',  'A'];
const array2 = Uint8Array.from([1, 2, 3]);
const result = [...array1, ...array2];
console.log(result); // ["B", "g", "R", "a", 1, 2, 3]

  • Related