4

Say I have the following object:

var obj = { foo: 'bar' };

I want to add this object to an array X amount of times so the result is:

[{ foo: 'bar' }, { foo: 'bar'}, ... , { foo: 'bar'}]

Is there a way to accomplish this without explicitly coding a loop?

6
  • is fiveHundredChars the array you want to insert the object into? Commented Nov 3, 2014 at 4:47
  • 4
    Is this just in an attempt to make the code look more concise? Any solution you come up with is likely to have a loop-like implementation in the background, so there won't be any difference in theoretical or practical efficiency. If you're doing this more than once in your code you can just define a function for it so you don't repeat the loop. Commented Nov 3, 2014 at 4:50
  • @nbrooks, yes you're correct regarding code looking more concise. Commented Nov 3, 2014 at 4:54
  • Suppose you could do the same as the trick with the string (often used to generate padding).. Then since it would be an object, you would have filled your array with 500 references to the same object. Is this your intention? edit Why did you remove that example with the string? Commented Nov 3, 2014 at 4:55
  • why don't you build a function? and what do you want exactly (the benefit)? Commented Nov 3, 2014 at 4:58

8 Answers 8

11

There is a way: manually. Any programmatic solution will indeed use a loop here, which, if you wish to maintain your sanity -- use it.

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

1 Comment

I was thinking about saying that.
7

You can use map

var filled = Array.apply(null, Array(501)).map(function() { return {"foo":"bar"} });

3 Comments

Plot twist: this is still a loop
Sad thing is the OP is not looking to not loop. What the OP wants is to try to make the code look "cleaner" which is reality means making it more confusing to read. Now is this slower over a while loop? I am too lazy to jsperf it.
@epascarello yeah, this is definitly a good method, but OP is trying to programmatically kill himself.
4

You can do this using .fill

const someArray = ['test']; // Any other data you may have
const resultingArray = new Array(100).fill({ foo: 'bar' }).concat(someArray);

Set 100 to whatever number you need, concat any extra data after (or before if needed)

As @isvforall pointed out this isn't a deep copy and is done via reference so changing any of the elements in the array would affect all of the others which reference the same object. Best used if your values are primitives.

2 Comments

Array.fill doesn't do a deep copy. All references to the same object. If you change one object the everyone will be the same
@isvforall fair enough, and good catch, not sure it's worth a downvote since the user never said they would be modifying the array or object however it is worth noting for sure.
2

I think epascarello's answer is already a winner, and I +1'd it, but here's another approach just for kicks, using your Array.join() trick along with JSON.stringify() and JSON.parse().

Verbose:

var obj = { foo: 'bar' };
var objJSON = JSON.stringify(obj);
var list = new Array(501).join(objJSON + ',')
var trimmedList = list.substr(0, list.length - 1); // getting rid of that last comma
var arrayJSON = '[' + trimmedList + ']';
var array = JSON.parse(arrayJSON);
console.log(array);

Compact:

var list = new Array(501).join(JSON.stringify({ foo: 'bar' }) + ',')
var array = JSON.parse('[' + list.substr(0, list.length - 1) + ']');
console.log(array);

3 Comments

Still a plot twist: yet another loop
+1 for originality and thinking outside the box (and proving in the process the OP is better of with less work and clearer code in the form of a loop (tucked away in a function to maintain readability in his main routine)).
2

If you really don't want a loop you can use recursion.

function objFillArray(obj, count) {
    let ret = [];
    return notALoop();
    function notALoop() {
        ret.push(obj);
        if( --count ) return notALoop();
        return ret;
    }
}

this will keep calling notALoop count number of times adding the object to the returned array.

Comments

1

Using recursion and concat function

var obj = { foo: 'bar' };

var result = (function fill(a, len) {
    return a.length == len ? a : fill(a.concat(obj), len);
})([], 10);

var obj = { foo: 'bar' };

var result = (function fill(a, len) {
    return a.length == len ? a : fill(a.concat(obj), len);
})([], 10);

document.write(JSON.stringify(result));

Comments

0

The callback function in Array.from can be used to ensure each element of the array is a different reference.

const arr = Array.from({length: 5}, _=>({foo: 'bar'}));
console.log(arr);

If all elements are meant to be the same reference, directly use Array#fill.

const arr = Array(5).fill({foo: 'bar'});
console.log(arr);

Comments

-1

Use .push() function to assign value to an array.

    yourarray.push(yourobject);
               |
               |
               |
               V
    fiveHundredChars.push(obj);

4 Comments

so.. you type this 500 times? Ok, it's not a loop, but you must be joking right? :)
I don't get what Andrew's meant -_-
So why did you post an answer?
I think loop is the efficient way to do it.

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.