Petah
Petah

Reputation: 46040

How to zip (compress) a JS array

How would I compress an array?

I am trying to compress an array. I have tried using the lz-string library and converting to/from strings, but I get null/0/[] on decompress.

This is what I'm doing:

var array = [];
for (var i = 0; i < 1024; i++) {
    array[array.length] = i % 255;
}
var string = String.fromCharCode.apply(null, array);
var compressed = LZString.compress(string);
var decompressed = LZString.decompress(compressed);
var dearray = [];
for (var i = 0; i < decompressed.length; i++) {
    dearray[i] = decompressed.charCodeAt(i);
}

http://jsfiddle.net/ZV5Za/18/

Upvotes: 2

Views: 7831

Answers (2)

Petah
Petah

Reputation: 46040

Turns out it does work, I just had a typo.

http://jsfiddle.net/ZV5Za/20/

var array = [];
for (var i = 0; i < 1024; i++) {
    array[array.length] = i % 255;
}
var string = String.fromCharCode.apply(null, array);
var compressed = LZString.compress(string);
var decompressed = LZString.decompress(compressed);
var dearray = [];
for (var i = 0; i < decompressed.length; i++) {
    dearray[i] = decompressed.charCodeAt(i);
}
console.log(array.length, array);
console.log(string.length, string);
console.log(compressed.length, compressed);
console.log(decompressed.length, decompressed);
console.log(dearray.length, dearray);

Upvotes: -1

Cerbrus
Cerbrus

Reputation: 72839

The problem seems to be in the way you're forming the array into a string, and back.

Why not use String.prototype.split() / Array.prototype.join() (Fiddle):

var string = array.join('|');
var dearray = decompressed.split('|');

Or maybe even better: JSON.stringify() / JSON.parse() (Fiddle)
(This actually preserves data types):

var string = JSON.stringify(array);
var dearray = JSON.parse(decompressed);

I don't know how you'd fix the "string -> array" step you are using, though.

Upvotes: 2

Related Questions