Bwyss
Bwyss

Reputation: 1834

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:

W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748

I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...] I have this snippet that does the trick, but only for the first value:

var foo = str.substring(str.indexOf(":") + 1);

Upvotes: 2

Views: 101

Answers (4)

Florent
Florent

Reputation: 12420

Use split().
Demo here: http://jsfiddle.net/y9JNU/

var keys = [];
var values = [];

str.split(', ').forEach(function(pair) {
  pair = pair.split(':');
  keys.push(pair[0]);
  values.push(pair[1]);
});

Without forEach() (IE < 9):

var keys = [];
var values = [];
var pairs = str.split(', ');

for (var i = 0, n = pairs.length; i < n; i++) {
  var pair = pairs[i].split(':');
  keys.push(pair[0]);
  values.push(pair[1]);
};

Upvotes: 7

Jonathan
Jonathan

Reputation: 1833

JSFiddle

var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";

var all = str.split(","),
    arrayOne = [],
    arrayTwo = [];

for (var i = 0; i < all.length; i++) {
    arrayOne.push(all[i].split(':')[0]);  
    arrayTwo.push(all[i].split(':')[1]);
}

Upvotes: 1

maček
maček

Reputation: 77778

This will give you the keys and values arrays

var keys   = str.match(/\w+(?=:)/g),
    values = str.match(/[\d.]+(?=,|$)/g);

RegExp visuals

/\w+(?=:)/g

/\w+(?=:)/g

/[\d.]+(?=,|$)/g

/[\d.]+(?=,|$)/g


And another solution without using regexp

var pairs  = str.split(" "),
    keys   = pairs.map(function(e) { return e.split(":")[0]; }),
    values = pairs.map(function(e) { return e.split(":")[1]; });

Upvotes: 4

qiu-deqing
qiu-deqing

Reputation: 1333

parse the string to an array

var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";

var tokens = str.split(",");

var values = tokens.map(function (d) {
    var i = d.indexOf(":");
    return +d.substr(i + 1);
});

var keys = tokens.map(function (d) {
    var i = d.indexOf(":");
    return d.substr(0, i);
});

console.log(values);
console.log(keys);

http://jsfiddle.net/mjTWX/1/ here is the demo

Upvotes: 0

Related Questions