Printing array list with quotes

I have the following JS Fiddle : https://jsfiddle.net/walker123/f5aktcnm/2/

Code Below:

var list = [];
var startYear = 2010;
// returns the year (four digits)
var currentTime = new Date()
var currentYear = currentTime.getFullYear();

console.log(startYear);
console.log(currentYear);
for (var i = startYear; i <= currentYear; i++) {
    list.push(i);
} 

console.log("Printing List array");
console.log(list);

It prints the list array like the following:

[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]

However, I am looking for something like this:

`[β€˜2010’, β€˜2011’, β€˜2012’ ,β€˜2013’,β€˜2014’,β€˜2015’, β€˜2016’,β€˜2017’,β€˜2018’,β€˜2019’,β€˜2020’,β€˜2021’];

How can I have quotes for each values? I tried .toString() method but that adds double quotes only at the start and end

The array is pushing the value as it currently exists. Since the value being pushed is numeric, no quotes. Change it to.

list.push(i.toString());
2 Likes

Hi @Jack_Tauson_Sr, so you called toString() on the array? You’d have to call it on the element you’re pushing:

list.push(i.toString())

Or, stringify each value afterwards using map():

console.log(list.map(String))

The latter would have the advantage that the original list still holds the numeric values, so you can still sort it differently later (for example).

Edit: x-post :-)

1 Like

Hi @m3g4p0p ,

Thanks for pointing that out. It works now. Appreciate your inputs.

Thanks @DaveMaxwell for your valuable input. It is working now.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.