Create Duplicate Objects Into Array Based On Length Provided
I want to insert duplicate values into array based on length provided like this: var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];; var dataTypesLength=
Solution 1:
Just loop the array of objects and use fill
to get your result.
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];
var dataTypesLength= 4;
var arr=[];
functionfillArray(value, len) {
returnArray(len).fill(value);
}
for (var i=0; i<a.length; i++){
var b = fillArray(a[i],dataTypesLength);
arr.push(...b);
}
console.log(arr);
Solution 2:
You can use this (single line solution):
a.reduce((acc,x)=>{ acc.push(...new Array(dataTypesLength).fill(x)); return acc;}, [])
Explaination :
- Reducing the input array starting from empty array []
- For every element creating a new array with length dataTypesLength and filling all the new array with the current element new Array(dataTypesLength).fill(x)
- Spread the new created array and push it into accumulator array acc.push(...new Array(dataTypesLength).fill(x))
- Return the accumulator array
Solution 3:
You can use map
with Object.assign
so that each object will have independent reference
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];
var dataTypesLength= 4;
a= a.map(obj => { returnArray(dataTypesLength).fill(null).map( e =>Object.assign({}, obj)) }).flat();
console.log(a)
Solution 4:
you can try reduce
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];;
var dataTypesLength= 4;
a = a.reduce(
(f,obj ) => {
var dup = newArray(dataTypesLength);
f.push(...dup.fill(obj));
return f;
}, [] )
Post a Comment for "Create Duplicate Objects Into Array Based On Length Provided"