34

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.

0

11 Answers 11

72

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.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 for cleverness and for mentioning that using the loop makes the intent clear.
This is a cool idea :-) That second function looks familiar ;-)
(Quietly waits for someone to pick up on the by one index offset)
I think you meant Array(n).join('.').split('.') also :)
split('.') fixed the off-by-one error with the original split('')
|
27

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

const arr = Array(size).fill("");

4 Comments

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!
What does this answer add that wasn't already better expressed in the accepted answer?
@Mogsdad The intent is way clearer and it's more readable. Best answer IMHO.
PS: This returns any[] not string[]
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(" ");

1 Comment

(Produces 1001 empty strings.)
3

You can try to do it by this way:

let n = 1000;
var emptyStrings = [...Array(n)].map(() => '')

Comments

3

Using Array.from;

const n = 5;
const arr = Array.from({length: n}).map(el => "")
console.log(arr)

1 Comment

This is the shortest answer I was looking for. Thanks @Sahin.
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;
}

Comments

0

You could do something like this:

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

1 Comment

In case anyone wonders how it works stackoverflow.com/questions/18947892/… :)
0

Just for fun

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

2 Comments

+1 for clever trick with valueOf. Side note - new is redundant here.
A bit shorter: String(Array([length])).split(',').map(String.prototype.valueOf,'')
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/

1 Comment

Save three chars with some golfing ;-) [1..5].map(-> '')
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))]

1 Comment

These are no longer part of ECMAScript 6. (Considered for ES7)
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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.