Skip to content

Instantly share code, notes, and snippets.

@Brocco
Created February 8, 2017 18:03
Show Gist options
  • Save Brocco/602b56b69573788fd18b2c0affbd2913 to your computer and use it in GitHub Desktop.
Save Brocco/602b56b69573788fd18b2c0affbd2913 to your computer and use it in GitHub Desktop.
Organizing array of [r, g, b, a, r, g, b, a] to an object array [{r, g, b, a}, {r, g, b, a}]
const pixels = ['r','g','b','a','r','g','b','a','r','g','b','a'];
const propMap = ['r', 'g', 'b', 'a'];
const rgbas = pixels.reduce((acc, curr, i) => {
const mod = i%4;
switch (mod) {
case 0:
return [...acc, {r: curr}];
default:
const index = Math.floor(i/4);
const color = acc[index];
color[propMap[mod]] = curr;
return acc;
}
}, []);
console.log(rgbas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment