I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values.
Check out my code snippet below:
const data = [
{ index: 1, value: "111" },
{ index: 2, value: "121" },
{ index: 3, value: "111" },
{ index: 5, value: "111" },
{ index: 6, value: "121" },
{ index: 7, value: "121" },
];
const getGroupBy = (data) => {
return data.reduce((acc, curr, currIndex, arr) => {
const val = curr.value;
const idx = curr.index;
const fValues = arr.filter((el) => el.value === val).map(el => el.index);
if (acc.hasOwnProperty(currIndex)) {
acc[currIndex] = arr.filter((el) => el.value === val);
} else {
Object.assign(acc, { [0]: [idx] });
}
return acc;
}, {});
};
console.log(getGroupBy(data));
The expected output from my code is :
{
0: [1,3,5],
1: [2,6,7]
}