Kavitha K
Kavitha K

Reputation: 75

How to split value from a string and push into array in javascript

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"];

Upvotes: 0

Views: 2079

Answers (4)

brk
brk

Reputation: 50291

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);

Upvotes: 0

pacukluka
pacukluka

Reputation: 735

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);

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

Try this:

var values="test1,test2,test3,test4,test5";
var arrP = [];
var newVal = values.split(',');
arrP.push(...newVal);
console.log(arrP);

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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"]

Upvotes: 0

Related Questions