Home » Nodejs » Creating array of empty strings?

Creating array of empty strings?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

Answers:

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.

Questions:
Answers:

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(" ");

Questions:
Answers:

You could make a function out of it:

function stringArray(length) {
    var arr = [];
    for(var i = 0; i < length; ++i) { arr.push(''); }
    return arr;
}

Questions:
Answers:

You could do something like this:

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

Questions:
Answers:

Just for fun

var empty = Array.apply(null, new Array(someLength)).map(String.prototype.valueOf,"");

Questions:
Answers:

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/

Questions:
Answers:

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))]