3

I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?

e.g : var strVale = "130,235,342,124 ";

1
  • strVale.split(',') will give you an array of values Commented Oct 5, 2017 at 6:43

4 Answers 4

3

You can split and then use parseInt to convert it into integer array.

//get this from localStorage
var strValue = "130,235,342,124"; 
var res = strValue.split(',').map(x=>{return parseInt(x)});
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

1

Is there a simple way to do that? Yes! Just use 2 simple functions: concat and split:

var str = "130,235,342,124";
var arr = [1,2,3];
arr = arr.concat(str.split(','));

//result:
//arr = ["1", "2", "3", "130", "235", "342", "124"];

EDIT: for integer arrays (just add map function):

var str = "130,235,342,124";
var arr = [1,2,3];
arr = arr.concat(str.split(',').map(Number));

//result:
//arr = [1, 2, 3, 130, 235, 342, 124];

Comments

1

You can use javascript split function like:

 var strVal = "130,235,342,124";
 console.log(strVal.split(','));

Comments

0

Beside the fact you can use myValues.split(",") to get the array - one common use of localStorage is to store your array as String like:

var myArray = [130,235,342,124];

// Send Array to localStorage:
localStorage.myStuff = JSON.stringify( myArray );

// Get Array from localStorage
myArray = JSON.parse( localStorage.myStuff );

Another common fallback to empty array on application init is:

// get array from localStorage or set to empty array:
var myArray = JSON.parse( localStorage.myStuff || "[]" );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.