Reputation: 7018
I want to insert duplicate values into array based on length provided like this:
var a = ['bar', 'google', 'mod'];
var b = [];
var dataLength = 4;
output should look like: var a = ['bar', 'bar','bar','bar', 'google', 'google', 'google', 'google', 'mod', 'mod','mod', 'mod'];
I tried this:
var dataLength = 4;
var a = ['bar', 'google', 'mod'];
var b = new Array(dataLength);
var c = [];
for (let i = 0; i < a.length; i++) {
c.push((b.fill(a[i]).toString()))
}
It works but not sure this is a good way to do this.
Upvotes: 0
Views: 150
Reputation: 50797
A fairly simple technique is just to use flatMap
with Array.prototype.fill
:
const repeatN = (n, arr) => arr .flatMap (a => Array (n) .fill (a) )
console .log (
repeatN( 4, ['barclays', 'google', 'vod'] )
)
If your environment doesn't support flatMap
, it's not hard to shim, or you could use this instead:
const repeatN = (n, arr) =>
arr.map(a => Array (n) .fill (a)) .reduce ( (a, b) => a .concat (b) )
Upvotes: 1
Reputation: 8589
Two of our newest Array methods, flatMap() and fill() are perfect for this:
.flatMap()
will do a mapping and merge the returned arrays into one array.
.from()
can create a new array for a specific length.
.fill()
fills an array with a certain value.
So all 3 combined we get this little oneliner:
var a = ['barclays', 'google', 'vod'];
var length = 4;
var b = a.flatMap( word => Array.from({ length }).fill( word ));
console.log( b );
Upvotes: 1
Reputation: 4826
Try this:
const a = ["barclays", "google", "vod"];
const result = (num) => a.reduce((acc, ele) => acc.concat(Array(num).fill(ele)), []);
console.log(result(10))
Upvotes: 2
Reputation: 4296
var a = ['barclays', 'google', 'vod'];
var b = [];
var dataLength = 4;
for (let i = 0; i < dataLength; i++) {
for (let o = 0; o < a.length; o++){
b.push(a[o]);
}
}
console.log(b);
Something like this,except in my example its not sorted.
Upvotes: 0
Reputation: 1716
Add nested for loop, loop through your data length and push the element in your array.
var a = ['barclays', 'google', 'vod'];
var b = [];
var dataLength = 4;
for (let i = 0; i < a.length; i++) {
for(let j=0;j<dataLength;j++) {
b.push(a[i])
}
}
Upvotes: 1
Reputation: 5122
var a = ['barclays', 'google', 'vod'];
var b = [];
var dataLength = 4;
// Loop every element of a
for (let i = 0; i < a.length; i++) {
// Loop 4 times and push current element
for (let j = 0; j < dataLength; j++) {
b.push(a[i])
}
}
console.log(b)
Upvotes: 2