I have an Array of objects and I need to return this collection like Object and they key-names need to be indexes of length. I need to filter this object for it values.
Here is my code:
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));
My expected output is :
{
0: [1,3,5],
1: [2,6,7]
}
4
Answers
Is this not more useful, to key the arrays by their values instead of 0,1?
Anyway here is how to reduce and how to get either 0,1 keyed or keyed on value
Interesting method suggested here
You could group and assign the values to an object.
I think you have to go through the step
this step is help your code more cleaner
The following code, I used reduce but last iteration, I changed the output to the desired one.
This is useful manytimes to get the desired output. when index is for last item, we are done with all the elements.