Reputation: 45
I have a cmyk array which is :
cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]
and the other one is the number array which is:
arrGeo = [4,2,1]
I want to have an array which has iterative cmyk respect to arrGeo numbers which means:
cmykArray = [
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,],
[0,0,1,1,0,0,1,1],
[0,0,0,1]
]
and this is my code to make it :
for (let i = 0; i < arrGeo.length; i++) {
var cmyk = [];
var cmykArray = [];
for (let j = 0; j < arrGeo[i].length; j++) {
for (let k = 0; k < 4; k++) {
cmyk = cmyk.concat(cmykColor[i][k]);
console.log(hex[i]);
}
}
cmykArr.push(cmyk);
}
Upvotes: 2
Views: 52
Reputation:
Here's a very succinct solution:
const cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]
const arrGeo = [4,2,1]
const result = cmykColor.map((arr, i) =>
[...Array(arrGeo[i])].reduce(res => [...res, ...arr], [])
)
console.log(result);
It uses an empty array as a means for .reduce()
to copy the current array into a result array the proper number of times.
But the primary idea is to use .map()
because the entire purpose of a .map()
call is to create a new array with the same length as the one it's called on, but with a new value at each index.
So cmykColor
wants to "map" each of its arrays to a new array that has the content spread out the proper number of times.
And we can make it slightly more efficient by reusing the original array as the seeded value to .reduce()
.
const cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]
const arrGeo = [4,2,1]
const result = cmykColor.map((arr, i) =>
[...Array(arrGeo[i] - 1)].reduce(res => [...res, ...arr], arr)
)
console.log(result);
You could also just map each cmykColor
array the proper number of times to a new array, and make those arrays the arguments to .concat()
.
const cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]
const arrGeo = [4,2,1]
const result = cmykColor.map((arr, i) =>
[].concat(...[...Array(arrGeo[i])].map(_ => arr))
)
console.log(result);
But then .concat()
is an old school way to do this. You can now use .flat()
.
const cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]
const arrGeo = [4,2,1]
const result = cmykColor.map((arr, i) =>
[...Array(arrGeo[i])].map(_ => arr).flat()
)
console.log(result);
Upvotes: 1
Reputation: 3338
One liner:
cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]];
arrGeo = [4,2,1];
cmykArray = [];
arrGeo.forEach(function (item, index) {
cmykArray[index] = [].concat.apply([], Array(item).fill(cmykColor[index]));
});
console.log(cmykArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
/** Thanks Nina :) **/
Upvotes: 1
Reputation: 386680
You could map with another loop for the wanted count.
const
cmykColor = [[0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]],
arrGeo = [4, 2, 1],
result = cmykColor.map((a, i) => {
let c = arrGeo[i],
t = [];
while (c--) t.push(...a);
return t;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 4