I have one array like this:
temp = [
'data1',
['data1_a','data1_b'],
['data2_a','data2_b','data2_c']
];
//
I want to change the array within my array using toString(), how the best to do it? Then the array like :
temp = [
'data1',
'data1_a,data1_b',
'data2_a,data2_b,data2_c
];
Jan Černý
1,4162 gold badges22 silver badges39 bronze badges
4 Answers 4
use map and get that desired output. No need for any other complex methods or functions,
var temp = [
'data1',
['data1_a','data1_b'],
['data2_a','data2_b','data2_c']
];
var res = temp.map((item) => item.toString());
console.log(res);
answered Apr 23, 2018 at 10:15
Ankit Agarwal
30.8k5 gold badges41 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Just map it and return the stringified version. There's no need for any checks - the strings will just be unmodified, the arrays will be converted like you want them
temp = [
'data1', ['data1_a', 'data1_b'],
['data2_a', 'data2_b', 'data2_c']
];
let foo = temp.map(String);
console.log(foo);
answered Apr 23, 2018 at 10:17
baao
73.6k18 gold badges153 silver badges209 bronze badges
1 Comment
ikwijaya
but if i provide NULL in array, this NULL will be 'null', how to give this empty??
You can use .map() with .join():
let temp = [
'data1',
['data1_a','data1_b'],
['data2_a','data2_b','data2_c']
];
let result = temp.map(v => Array.isArray(v) ? v.join(",") : v);
console.log(result);
Docs:
answered Apr 23, 2018 at 10:12
Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
Comments
Use this
temp = [
'data1',
['data1_a','data1_b'],
['data2_a','data2_b','data2_c']
];
for(var i = 0; i < temp.length; i ++) {
temp[i] += "";
}
console.log(temp);
answered Apr 23, 2018 at 10:14
Saeed
5,4983 gold badges31 silver badges43 bronze badges
Comments
lang-js