27

Is there an easy way to create an array of empty strings in javascript? Currently the only way I can think to do it is with a loop:

var empty = new Array(someLength);
for(var i=0;i<empty.length;i++){
    empty[i] = '';
}

but I'm wondering if there is some way to do this in one line using either regular javascript or coffeescript.

Abe Miessler
  • 79,479
  • 96
  • 291
  • 470

10 Answers10

65

Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.


Yes, there is a way:

 var n = 1000;
 Array(n).join(".").split("."); // now contains n empty strings.

I'd probably use the loop though, it conveys intent clearer.

function repeat(num,whatTo){
    var arr = [];
    for(var i=0;i<num;i++){
        arr.push(whatTo);
    }
    return arr;
}

That way, it's perfectly clear what's being done and you can reuse it.

Benjamin Gruenbaum
  • 260,410
  • 85
  • 489
  • 489
  • 4
    +1 for cleverness and for mentioning that using the loop makes the intent clear. – Vivin Paliath Nov 15 '13 at 17:54
  • 1
    This is a cool idea :-) That second function looks familiar ;-) – qwertynl Nov 15 '13 at 17:54
  • 3
    *(Quietly waits for someone to pick up on the by one index offset)* – Benjamin Gruenbaum Nov 15 '13 at 17:57
  • 1
    I think you meant `Array(n).join('.').split('.')` also :) – nderscore Nov 15 '13 at 17:57
  • `split('.')` fixed the off-by-one error with the original `split('')` – joeytwiddle Apr 07 '16 at 07:18
  • This created a very nice array of empty strings for me, but still not getting the push values recognized. `// Initialize empty array of strings let faceIds = Array(faces.length).join(".").split(".") for (let face of faces) { faceIds.push(face.faceId) console.log(face.faceId) } return facesIds;` It crashes and says `faceIds` are undefined. – Azurespot Oct 08 '19 at 00:32
16

You can get an array defining the size and fill it with some tokens:

const arr = Array(size).fill("");
Mir-Ismaili
  • 10,843
  • 5
  • 65
  • 90
user2592256
  • 197
  • 1
  • 4
  • Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar or using Ctrl+K on your keyboard to nicely format and syntax highlight it! – WhatsThePoint Mar 01 '18 at 15:08
  • 1
    What does this answer add that wasn't already better expressed in the accepted answer? – Mogsdad Mar 01 '18 at 19:20
  • 1
    @Mogsdad The intent is way clearer and it's more readable. Best answer IMHO. – dan-klasson Dec 12 '18 at 23:02
  • PS: This returns `any[]` not `string[]` – Darvesh Feb 15 '21 at 06:27
13

here's a simpler way using generic protos on Array and String:

"".split.call(Array(1001), ",")

EDIT: There's now even simpler ways, some of which are readable:

Array(1000).fill("");

" ".repeat(999).split(" ");
dandavis
  • 15,617
  • 5
  • 38
  • 36
3

You can try to do it by this way:

let n = 1000;
var emptyStrings = [...Array(n)].map(() => '')
Vlad Hilko
  • 964
  • 10
  • 15
3

Using Array.from;

const n = 5;
const arr = Array.from({length: n}).map(el => "")
console.log(arr)
Sahin Erbay
  • 924
  • 2
  • 12
  • 22
0

You could make a function out of it:

function stringArray(length) {
    var arr = [];
    for(var i = 0; i < length; ++i) { arr.push(''); }
    return arr;
}
qwertynl
  • 3,842
  • 1
  • 20
  • 43
0

You could do something like this:

var someLength = 10;
var empty = Array.apply(0, Array(someLength)).map(function(){return '';});
// result: ["", "", "", "", "", "", "", "", "", ""]
nderscore
  • 4,112
  • 19
  • 29
0

Just for fun

var empty = Array.apply(null, new Array(someLength)).map(String.prototype.valueOf,"");
epascarello
  • 195,511
  • 20
  • 184
  • 225
0

The easiest thing to do in CoffeeScript is to use a loop comprehension:

a = ('' for i in [0 ... someLength]) # Note: 3 dots
a = ('' for i in [1  .. someLength]) # Or 2 dots and start at 1
#...

Demo: http://jsfiddle.net/ambiguous/b9Vj9/

mu is too short
  • 413,090
  • 67
  • 810
  • 771
0

Although not widely available, once browsers start supporting EcmaScript 6 array comprehensions, you will be able to do something along the lines of:

var n = 1000;
var empty_strs = ['' for (x of new Array(n))]
rdodev
  • 3,126
  • 3
  • 25
  • 33