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.
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.
Share Improve this question asked Mar 7, 2016 at 23:30 thatOneGuythatOneGuy 10.6k9 gold badges58 silver badges92 bronze badges 9- does order matter? if not, concat three repeats. – dandavis Commented Mar 7, 2016 at 23:31
- Possible duplicate: stackoverflow./questions/6310206/iterate-a-script-x-times – jdabrowski 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. – thatOneGuy Commented Mar 7, 2016 at 23:32
-
1
("first,".repeat(30)+"second,".repeat(40)+"third,".repeat(50)).slice(0,-1).split(",")
– dandavis Commented Mar 7, 2016 at 23:33 - 1 @dandavis this works for these inputs, but would break if the inputs contained mas. – Ahmad Mageed Commented Mar 7, 2016 at 23:59
5 Answers
Reset to default 3This 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();
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 mas, since we're not taking an approach that splits on mas similar to the solution in the ments 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]
I'm not sure that I pletely 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' ]
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);
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).