我有一个对象数组,我需要像对象一样返回这个集合,它们的键名需要是长度的索引。我需要过滤这个对象的值。这是数组:
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" },
];
reduce怎么做?
我期望得到的:
{
0: [1,3,5],
1: [2,6,7]
}
我的错误代码:
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;
}, {});
};
您可以分组并将值分配给一个对象。
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" }],
result = Object.assign(
{},
Object.values(data.reduce((r, { index, value }) => ((r[value] ??= []).push(index), r), {}))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
用值而不是 0,1 键控数组不是更有用吗?
无论如何,这里是如何减少以及如何获得 0,1 键控或键控值
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 indicii = data.reduce((acc,{index,value}) => {
(acc[value] ??= []).push(index);
return acc;
},{})
console.log({...Object.values(indicii)})
// or
console.log(indicii);
我认为你必须经过这一步
这一步是为了让你的代码更简洁
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) => {
if (acc[curr.value]) acc[curr.value].push(curr.index);
else acc[curr.value] = [curr.index];
return acc;
}, {});
};
console.log(getGroupBy(data));
console.log({ ...Object.values(getGroupBy(data)) });