3

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
swat
  • 69
  • 4
  • Side note: [Don't use `for in` to iterate over arrays](https://stackoverflow.com/a/500531/227299) – Ruan Mendes Jun 16 '17 at 13:49
  • "I tried using the slice method in javascript, but it fails" Numbers ain't Strings. You should be aware of the types you're dealing with. – Thomas Jun 16 '17 at 15:25
  • For your next questions: don't just say it fails. Specify how it fails, does it give you wrong results? Does it throw an exception? What's the error message? Had you done that, you may have answered your own question because the console should say: `Uncaught TypeError: dates[i].slice is not a function` https://stackoverflow.com/help/how-to-ask – Ruan Mendes Jun 16 '17 at 15:52

2 Answers2

3

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));
}
Arg0n
  • 8,283
  • 2
  • 21
  • 38
2

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('-'); }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • It's cool, but back references in RegExp make the code hard to read... At least for me. I think I see what it's doing (the two dots are the last two elements?) but slice is so much clearer. – Ruan Mendes Jun 16 '17 at 13:56
  • it just looks if there are two characters left of the right, then replace ther, ort split. – Nina Scholz Jun 16 '17 at 13:58
  • This solution work fine in chrome, however fails in IE. IE does not recognize result = dates.map(a => a.toString().split(/(?=..$)/).join('-')); – swat Jun 22 '17 at 13:35
  • It does not recognize => symbol. Is there an alternative? – swat Jun 22 '17 at 13:36
  • @swat, you could use the classic function expression instead of an arrow function, please see edit. – Nina Scholz Jun 22 '17 at 15:03