JSFiddle - React, Tailwind, and code Playground
by pmiranda
JavaScript
// I have an array of objects like this:
const arrayOfObjects = [
{ A: 1, B: 2, C:3 },
{ A: 3, B: 4, C:1 }
]
// And another array which is called "headers"
const headers = [
['A', 'B'],
['C']
]
// I have to create an array similar to the first one but, with those objects splited by what `headers` have in it's arrays.
// This should be the goal:
const result = [
[
{ A: 1, B: 2 },
{ C:3 }
],
[
{ A: 3, B: 4 },
{ C:1 }
]
]
// I tried by doing a "base" array with:
const baseArray = []
headers.forEach((header) => {
const objFromHeader = {};
header.forEach((head) => {
objFromHeader[head] = 0;
});
baseArray.push(objFromHeader);
});
// That will give me the `result` array but with 0 values for each key.
// And then loop for the first array and put inside another array the base array with the correct values
console.log(baseArray);
console.log('Expected output - result: ', result)