I tried to split value from string and push into an array but not working. How to do it in javascript?
var values="test1,test2,test3,test4,test5";
var arrP=[];
var newVal=values.split(',');
arrP.push(newVal);
console.log(arrP);
Output should be,
arrP=["test1","test2","test3","test4","test5"];
4 Answers 4
Try this:
var values="test1,test2,test3,test4,test5";
var arrP = [];
var newVal = values.split(',');
arrP.push(...newVal);
console.log(arrP);
Comments
To add an array to an already existing array, use concat.
var values="test1,test2,test3,test4,test5";
var arrP=[];
var newVal=values.split(',');
arrP = arrP.concat(newVal);
console.log(arrP);
Comments
Simply do a split on ,. Because split(), divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array and that's what you want
var values="test1,test2,test3,test4,test5";
var expected = values.split(',');
console.log(expected)
With your existing code you will get with extra [] at start and end,
[["test1", "test2", "test3", "test4", "test5"]]
But I guess you want this,
["test1", "test2", "test3", "test4", "test5"]
Comments
This snippet var newVal=values.split(','); will create a new array since split creates a new array. So your code is pushing an array to another array
var values = "test1,test2,test3,test4,test5";
var newVal = values.split(',');
console.log(newVal);
To fix that you need to iterate that array and push those values. If map is used then no need to declare an array since map returns a new array
var values = "test1,test2,test3,test4,test5".split(',').map(item => item)
console.log(values);
newVal, assplitdoes exactly what you need.newVal.arrP.push(...newVal)orarrP = arraP.concat(newVal);but only if arrayP have already elements if it's empty you don't need to do anything justarrP = values.split(',');var arrP=values.split(',');