Patrick Beardmore
Patrick Beardmore

Reputation: 1032

Javascript array creation

How do I turn this string: house,33;car,43;dog's,99; into this array: arr[33]="house" arr[43]="car" arr[99]="dog's" using javascript and jquery.

Once I have the array, can I store information (like a 0 or 1 flag) next to each?

Upvotes: 0

Views: 569

Answers (2)

Andrei
Andrei

Reputation: 4237

try this..

var initString = "house,33;car,43;dog's,99";
var array1 = initString.split(';')
var result = [];
    for(var i=0,l=array1.length;i<l;i++){
        var items = array1[i].split(',');
        result[parseInt(items[1])] = {flag:0, value:items[0]};
    }

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

var str = "house,33;car,43;dog's,99;";
var pieces = str.split(';');
var arr = new Array();
for (var index = 0; index < pieces.length; index++) {
    var halves = pieces[index].split(',');
    arr[ halves[1] ] = halves[0];
}

Though you really shouldn't be specifying the array index unless you have a complete list from 0 to 99 (your sample has only three entries, all of which are well into that sequence).

Upvotes: 1

Related Questions