4

Say I have an array :

var newArray = [];

I can add strings to it like so :

var thisString = 'watch';
newArray.push(thisString);

What I want to do is have an array of this string. So, for example, I want newArray to have 50 of these 'thisString'.

I can do this easily via a loop :

for(var i=0;i<50;i++){
  newArray.push(thisString);
}

But say if I have 3 strings :

var firstString = 'first', secondString = 'second', thirdString = 'third';

And I want to push the third one 30 times, second 40 times and third 50 times, is the only way of doing this via the loop above ? Or can I say

newArray.push(firstString * 50); //obviously not correct javascript (psuedo code)

I want to do this as in my project I could have over 10 strings. I know this is what loops are built for but I was wondering if there are simpler ways of doing this.

JQuery can be used.

9
  • does order matter? if not, concat three repeats. Commented Mar 7, 2016 at 23:31
  • Possible duplicate: stackoverflow.com/questions/6310206/iterate-a-script-x-times Commented Mar 7, 2016 at 23:31
  • @dandavis order doesn't matter as I will be going through the array randomly anyway and removing them after. Commented Mar 7, 2016 at 23:32
  • 1
    ("first,".repeat(30)+"second,".repeat(40)+"third,".repeat(50)).slice(0,-1).split(",") Commented Mar 7, 2016 at 23:33
  • 1
    @dandavis this works for these inputs, but would break if the inputs contained commas. Commented Mar 7, 2016 at 23:59

5 Answers 5

3

This is the coolest way I found to fill an array (size of 10) with the same string:

const array = new Array(10).fill('my-string-value');

So using this we can do:

const array = [
  ...new Array(10).fill('first'),
  ...new Array(5).fill('second'),
  ...new Array(20).fill('third'),
];

And if you want to do it generic you could do something like this:

const data = [
  { value: 'first', count: 10 }, 
  { value: 'second', count: 5 }, 
  { value: 'third', count: 20 },
];

const myArray = data.map(({ value, count }) => 
  new Array(count).fill(value)).flat();
Sign up to request clarification or add additional context in comments.

Comments

2

To get an array of repeated elements you can use this approach:

var count = 3;
var sizedArray = Array.apply(null, Array(count));

This returns the following:

[undefined, undefined, undefined]

Next, you can use map to project the intended value, effectively giving you an array of the value repeated count times:

var value = 'hello';
var result = sizedArray.map(function(o) {
    return value;
});
// ['hello', 'hello', 'hello']

Putting this all together, your request could be solved as follows:

function generateArray(value, size) {
  var sizedArray = Array.apply(null, Array(size));
  var result = sizedArray.map(function() {
    return value;
  });
  return result;
}

var firstArray = generateArray('first', 5);
var secondArray = generateArray('second', 10);
var thirdArray = generateArray('third', 15);
var result = firstArray.concat(secondArray).concat(thirdArray);
console.log(result);

This approach will work with any string, even those with commas, since we're not taking an approach that splits on commas similar to the solution in the comments which would work for a limited set of inputs.

JSBin: demo link

Alternately, if you're using LoDash, you could use the _.range method to generate an array to map on, which would replace my use of Array.apply above:

var range = _.range(4);
// [0, 1, 2, 3]

1 Comment

Now we can use the Spread Operator too, instead of Array.apply. It'll be like [...Array(3)]. A shorter way. Great answer :)
1

I'm not sure that I completely understand your desired output, but this might be the right code. This will create an array of c length and then populate each index with the String s.

function stringArrMaker(s, c) {
    return "#".repeat(c).split("").map(function () {
        return s;
    });
}

console.log(stringArrMaker("hello", 10));

This is a silly way to populate an array with c number of values. String.repeat() will take a String and "repeat" it within the String. So "#".repeat(3); creates ### and then you split() to create an Array of the length that you want.

Do note that String.repeat() does not have wide support. So you may want to prefer Array.apply(null, Array(count)); instead. I just use this for code golfing.

Output

[ 'hello',
  'hello',
  'hello',
  'hello',
  'hello',
  'hello',
  'hello',
  'hello',
  'hello',
  'hello' ]

6 Comments

what's the hash for after the first return ? DanDavis answered with a similar answer in the comments but this is cool given it's easily reusable :)
Sorry, I should have said what it did. See my edit.
so it should be s.repeat(c).split ... ? Could you elaborate on why it is 'silly' too ?
@thisOneGuy No, it needs to be a single character. The character doesn't matter. If you did s.repeat(3); You would get hellohellohello and the split() would be incorrect. You might be able to split it in a different manner and get the correct output though.
ahh sorry I get it now as you're using .map() yes? So it basically makes an array of hash's (#), and then overwrites each one with string s ?
|
0

I have no idea why what you're doing is practical at all, but maybe this would help:

function arrayOfSameStrings(repeatString, times){
  var r = [];
  for(var i=0,l=times; i<l; i++){
    r.push(repeatString);
  }
  return r;
}
var ary = arrayOfSameStrings('Bad Idea', 30);
console.log(ary);

Comments

0

why not do it like this. this is the easiest solution.

String.prototype.rtoArray = function(number) {
  retArray = Array();
  for (i = 0; i < number; i++) {
    retArray[i] = String(this);
  }
  return retArray;
}

firstString = "first".rtoArray(50);
secondString = "second".rtoArray(40);
thirdString = "third".rtoArray(30);

the result is firstString will have 50 times with the "first" string value, secondString will have 40 times with the "second" string value, and thirdString will have 30 times with the "third" string value. (results are in array).

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.