33

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
  • 82,532
  • 99
  • 305
  • 486

11 Answers11

71

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
  • 270,886
  • 87
  • 504
  • 504
  • 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
26

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

const arr = Array(size).fill("");
Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100
user2592256
  • 297
  • 3
  • 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
  • 3
    @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
15

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
  • 16,370
  • 5
  • 40
  • 36
3

You can try to do it by this way:

let n = 1000;
var emptyStrings = [...Array(n)].map(() => '')
Vlad Hilko
  • 1,104
  • 12
  • 17
3

Using Array.from;

const n = 5;
const arr = Array.from({length: n}).map(el => "")
console.log(arr)
Sahin Erbay
  • 994
  • 2
  • 12
  • 24
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,912
  • 1
  • 21
  • 43
0

You could do something like this:

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

Just for fun

var empty = Array.apply(null, new Array(someLength)).map(String.prototype.valueOf,"");
epascarello
  • 204,599
  • 20
  • 195
  • 236
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
  • 426,620
  • 70
  • 833
  • 800
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,164
  • 3
  • 26
  • 34
0

Easy enough.

  1. Array with a length of 10 items, filled with empty strings (""):

    Array.from({length: 10}).map( _ => "" );
    // Array(10) [ "", "", "", "", "", "", "", "", "", "" ]
    
  2. Array with a length of 10 items, filled with numbers from 0 to 9:

    Array.from({length: 10}).map( (_, index) => index );
    // Array(10) [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    
  3. Array with a length of 10 items, filled with numbers from 1 to 10:

    Array.from({length: 10}).map( (_, index) => index + 1 );
    // Array(10) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    
  4. Array with a length of 10 items, filled with string containing "Chapter (1 ... 10).":

    Array.from({length: 10}).map( (_, index) => `Chapter ${index + 1}.` );
    // Array(10) [ "Chapter 1.", "Chapter 2.", "Chapter 3.", ... ]
    

(Using _ here as we don't use the value anyway.)

Ricardo
  • 61
  • 5