js array object same month classification

//数据
const List=[
    {id: '1',key: '2022-08-09', value: '明月'}, 
    {id: '3',key: '2022-08-24', value: '可欣'}, 
    {id: '2',key: '2022-02-16',value: '小红'}, 
    {id: '1',key: '2022-02-05', value: '小馨'},
    {id: '1',key: '2022-08-27',value: '小静'}]

 for (var i = 0; i < List.length; i++) {
        var time1 = time(List[i]);
        List[i].keyData = time1;
    }
function time(arr){
    var d = new Date(arr.key);
    var Year = d.getFullYear();
    var Month = d.getMonth()+1;
    var data = Year+"-"+Month;
    return data;
}
 
let key = {} //存储的 key 是type的值,value是在indeces中对应数组的下标
let indices = [] //数组中每一个值是一个数组,数组中的每一个元素是原数组中相同type的下标 
List.map((item, index) => {
    debugger
  //根据对应字段 分类(type)
  let type= item.keyData
  let _index = key[type]
  if (_index !== undefined) {
    indices[_index].push(index)
  } else {
    key[type] = indices.length
    indices.push([index])
  }
})
// 归类结果
let result = []
indices.map((item) => {
  item.map((index) => {
   //result.push(List[index]) //相同项排序在一起
  // if (item.length > 1) { result.push(List[index])} //只要重复项
  // if (item.length == 1){ result.push(List[index])} //只要单独项
 
   //我这里需要重复项 根据业务处理
   if (item.length > 1) {
    result.push(List[index])
   }
 })
})
console.log(key);
console.log(indices);
console.log(result);

Guess you like

Origin blog.csdn.net/qq_41954585/article/details/129158174