I am working with an array of objects, each containing the same properties. My goal is to create a function that will return an array of arrays, where each inner array holds values based on the property names of the objects.
Here is an example input:
input: [
{
test1: '10',
test2: '15',
test3: '14',
test4: '22'
},
{
test1: '4',
test2: '1',
test3: '45',
test4: '2'
},
{
test1: '5',
test2: '16',
test3: '7',
test4: '0'
}
]
The expected output should be an array of arrays where each sub-array contains only elements whose keys are the same. For instance, the values of test1
in an array would be: [10, 4, 5]
:
output: [[10, 4, 5], [15, 1, 16], [14, 45, 7], [22, 2, 0]]
My current approach involves using array.entries()
and iterator but the result is not correct as the values are stored in the incorrect order. Here is the snippet of code:
let output = [];
sort(input) {
const results = [[], [], [], []];
if (input.length > 0) {
const iterator = input.entries();
let item = iterator.next();
while (!item.done) {
const data = Object.values(item.value[1]);
results.forEach((result, index) => {
if (item.value[0] == index)
result.push(parseFloat(data[index]));
});
item = iterator.next();
}
}
output = results;
}
Can you suggest a way to make this function work correctly?