3

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.

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
  • does order matter? if not, concat three repeats. – dandavis Mar 07 '16 at 23:31
  • Possible duplicate: http://stackoverflow.com/questions/6310206/iterate-a-script-x-times – jdabrowski Mar 07 '16 at 23:31
  • @dandavis order doesn't matter as I will be going through the array randomly anyway and removing them after. – thatOneGuy Mar 07 '16 at 23:32
  • thanks @jdabrowski wasn't sure what to search for ill take a look – thatOneGuy Mar 07 '16 at 23:32
  • 1
    `("first,".repeat(30)+"second,".repeat(40)+"third,".repeat(50)).slice(0,-1).split(",")` – dandavis Mar 07 '16 at 23:33
  • @dandavis that's a nice answer indeed. You can add it as an answer rather than a comment as that does exactly what I asked for, all on one line :) – thatOneGuy Mar 07 '16 at 23:39
  • 1
    @dandavis this works for these inputs, but would break if the inputs contained commas. – Ahmad Mageed Mar 07 '16 at 23:59
  • @AhmadMageed it obviously won't work if the strings contained commas, but for the time being, in my situation, it works perfectly. Appreciate your answer too, and to be honest it's probably the safest :) But dandavis' answers it more efficiently :) – thatOneGuy Mar 08 '16 at 00:04
  • Possible duplicate of [Proper way to initialize an array's length in javascript?](http://stackoverflow.com/questions/4852017/proper-way-to-initialize-an-arrays-length-in-javascript) – zero298 Mar 08 '16 at 00:48

5 Answers5

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]
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • Now we can use the Spread Operator too, instead of Array.apply. It'll be like `[...Array(3)]`. A shorter way. Great answer :) – GiovannyLucas May 28 '22 at 03:20
2

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();
Technotronic
  • 8,424
  • 4
  • 40
  • 53
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' ]
zero298
  • 25,467
  • 10
  • 75
  • 100
  • 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 :) – thatOneGuy Mar 08 '16 at 00:23
  • Sorry, I should have said what it did. See my edit. – zero298 Mar 08 '16 at 00:27
  • so it should be s.repeat(c).split ... ? Could you elaborate on why it is 'silly' too ? – thatOneGuy Mar 08 '16 at 00:28
  • 1
    @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. – zero298 Mar 08 '16 at 00:31
  • 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 ? – thatOneGuy Mar 08 '16 at 00:32
  • @thisOneGuy [Ahmad Mageed's answer](http://stackoverflow.com/a/35856465/691711) is probably better though since [`String.repeat()` has bad support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Browser_compatibility). – zero298 Mar 08 '16 at 00:40
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).

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);
StackSlave
  • 10,613
  • 2
  • 18
  • 35