0

I need to convert number array to string array in angular.

Number string(getting data from server) look like:

"data": [
        957,
        958,
        959,
        960,
        961,
        963
    ],

I need to convert into :-

data=["957","958","959","960","961","963"]

I try but don't get success. Please help.

Neotrixs
  • 2,495
  • 4
  • 28
  • 58

3 Answers3

4

You can use map to iterate over array and return new array with converted values:

var dataNumbers = [
        957,
        958,
        959,
        960,
        961,
        963
    ];

var dataStrings = dataNumbers.map(function(value) {
 return String(value);
});

console.log(dataStrings);
Bartek Fryzowicz
  • 6,464
  • 18
  • 27
1

You can use Array.prototype.map() to create a new array.

Inside the callback function you can either use "" + o or use String(o)

var data= [
  957,
  958,
  959,
  960,
  961,
  963
];

console.log(data.map(o => ""+o));
console.log(data.map(o => String(o)));
Weedoze
  • 13,683
  • 1
  • 33
  • 63
1

To convert an int to string, there are many methods. Among them toString() seems to be the better option. You can find other possible methods here.

So now to iterate over an array, the better method is map() method. The idea is iterate over each element convert that element to string.


Here is the working snippet for you.

var data= [
  957,
  958,
  959,
  960,
  961,
  963
];

console.log(data.map(elt => String(elt)));

console.log(data.map(elt => elt.toString()));

console.log(data.map(elt => elt + ''));

console.log(data.map(elt => '' + elt));

Here is the same code using different types of iteration through loops.

var data= [
  957,
  958,
  959,
  960,
  961,
  963
];

new_data = []

for (let i of data) {
  new_data.push(i.toString()); 
}

console.log(new_data);


new_data = []

for (i = 0; i < data.length; i++) {
  new_data.push(data[i].toString()); 
}

console.log(new_data);

Hope this helps! :)

Community
  • 1
  • 1
bharadhwaj
  • 2,059
  • 22
  • 35