Input :
dates = [201701, 201702, 201703]
I want the output as [2017-01, 2017-02, 2017-03]
I tried using the slice method in javascript, but it fails
for (var i in dates) {
dates[i].slice(0, 4) + "-" + dates[i].slice(4);
}
It fails.
Input :
dates = [201701, 201702, 201703]
I want the output as [2017-01, 2017-02, 2017-03]
I tried using the slice method in javascript, but it fails
for (var i in dates) {
dates[i].slice(0, 4) + "-" + dates[i].slice(4);
}
It fails.
You just forgot toString()
:
var dates = [201701, 201702, 201703];
for (var i = 0; i < dates.length; i++) {
console.log(dates[i].toString().slice(0, 4) + "-" + dates[i].toString().slice(4));
}
You could use Number#toString
and String#replace
for the wanted dates.
var dates = [201701, 201702, 201703],
result = dates.map(a => a.toString().replace(/(?=..$)/, '-'));
console.log(result);
Or use String#split
.
var dates = [201701, 201702, 201703],
result = dates.map(a => a.toString().split(/(?=..$)/).join('-'));
console.log(result);
Both examples with ES5
var dates = [201701, 201702, 201703];
console.log(dates.map(function (a) { return a.toString().replace(/(?=..$)/, '-'); }));
console.log(dates.map(function (a) { return a.toString().split(/(?=..$)/).join('-'); }));