0

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
  • 1
    The result you'd like should be already into newVal, as split does exactly what you need. Commented May 12, 2020 at 15:38
  • Try and log newVal. Commented May 12, 2020 at 15:39
  • 1
    arrP.push(...newVal) or arrP = arraP.concat(newVal); but only if arrayP have already elements if it's empty you don't need to do anything just arrP = values.split(','); Commented May 12, 2020 at 15:40
  • var arrP=values.split(','); Commented May 12, 2020 at 16:06

4 Answers 4

2

Try this:

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

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

Comments

1

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

0

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

0

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

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.