按键分组对象数组-javascript

问题描述

之前,我确实在互联网上寻找其他答案,但仍然无法正常工作,我也不知道为什么

所以,我有一个包含对象的数组:

array =[
   {
      "name":"Alex","id":0
   },{
      "age":20,{
      "name":"John","id":1
   },{
      "age":30,"id":1
   }
]

我想根据他们的ID对他们进行分组,因此我希望结果是这样的:

array =[
   [
      {
         "name":"Alex","id":0
      },{
         "age":20,"id":0
      }
   ],[
      {
         "name":"John","id":1
      },{
         "age":30,"id":1
      }
   ]
]

我找到了解决类似问题的答案,所以尝试了一下,但不知道为什么不起作用

 array.reduce((a,value) => {
       a[value.id] = [...a[value.id] || [],value];
        return a;
    },[])

有人可以解释为什么吗?

解决方法

这是因为slider = alt.binding_range(min=2017,max=2018,step=1) select_year = alt.selection_single(name="year",fields=['year'],bind=slider,init={'year': 2017}) points = alt.Chart(data).mark_circle().encode( latitude="latitude:Q",longitude="longitude:Q",size='size:Q' ).transform_filter( select_year ).add_selection( select_year ) 不存在,因此其值始终为value.index

undefined更改为value.index,它将按预期工作。

value.id

,

您使用了错误的密钥-index,应将其更正为id

const array = [{
    "name": "Alex","id": 0
  },{
    "age": 20,{
    "name": "John","id": 1
  },{
    "age": 30,"id": 1
  }
]

const output = array.reduce((a,value) => {
  a[value.id] = [...a[value.id] || [],value];
  return a;
},[])

console.log(output);

,

在您的特定示例中,对象没有“索引”属性,因此,调用value.index时将得到undefined。如果您尝试将id字段用作最终数组的索引(这是我认为您要在reduce函数中尝试的内容),请尝试以下操作。请注意,如果您的对象中没有从0开始的连续ID,则将在最终数组中插入空值。您可以通过对最终数组进行类似array.filter((el) => el );的操作来删除它们。

array.reduce((a,value) => {
  if (a[value.id]) {
    a[value.id].push(value);
  } else {
    a[value.id] = [value];
  }
  return a;
},[]);
,

您实际上遇到了一个拼写问题,并通过编辑对其进行了修复,但是,如果要使其与任意ID一起使用(如注释所指出,01是有效的,并且“早期”数组索引),您可能要使用Map,并在末尾获取其values()

const array = [{
    "name": "Alex","id": 80
  },"id": 100
  },"id": 100
  }
]

const map = array.reduce((a,value) => {
  a.set(value.id,[...a.get(value.id) || [],value]);
  return a;
},new Map())
const output = Array.from(map.values());

console.log(output);