根据子对象数组的字段对对象数组进行排序

时间:2020-10-06 10:27:30

标签: javascript arrays sorting object

对不起,我的英语不好,希望大家理解。 我有一个数组:

const arr=[  
  {
    name:"c",
    pay:[{
      name:"c",
      date: "2020-10-02"
    },{
      name:"cc1",
      date: "2020-10-03"
    },{
      name:"cc2",
      date: "2020-09-28"
    }]
  },{
    name:"a",
    pay:[{
      name:"aa",
      date: "2020-10-05"
    },{
      name:"aa1",
      date: "2020-10-03"
    },{
      name:"aa2",
      date: "2020-10-04"
    }]
  }, {
    name:"b",
    pay:[{
      name:"bb",
      date: "2020-10-10"
    },{
      name:"bb1",
      date: "2020-10-04"
    },{
      name:"bb2",
      date: "2020-10-01"
    }]
  }
];
Const date= new Date("2020-10-05");

我想按日期字段对父元素进行排序。假设其日期最接近date变量的元素将是第一个 结果:

const arr=[
        {
    name:"a",
    pay:[{
      name:"aa",
      date: "2020-10-05"
    },{
      name:"aa1",
      date: "2020-10-03"
    },{
      name:"aa2",
      date: "2020-10-04"
    }]
  },{
    name:"b",
    pay:[{
      name:"bb",
      date: "2020-10-10"
    },{
      name:"bb1",
      date: "2020-10-04"
    },{
      name:"bb2",
      date: "2020-10-01"
    }]
  }, 
  {
    name:"c",
    pay:[{
      name:"c",
      date: "2020-10-02"
    },{
      name:"cc1",
      date: "2020-10-03"
    },{
      name:"cc2",
      date: "2020-09-28"
    }]
  }
]

我的想法是获取绝对值Math.abs(Aray中的date-field date),然后最小的父元素将排在最前面。但是我还没有处理每个子数组的逻辑。 请帮帮我。谢谢

2 个答案:

答案 0 :(得分:0)

我将创建一个执行您最近的日期逻辑的函数,在下面我将其称为absDate,然后可以将其传递给Array.sort

例如

const arr=[{name:"c",pay:[{name:"c",date:"2020-10-02"},{name:"cc1",date:"2020-10-03"},{name:"cc2",date:"2020-09-28"}]},{name:"a",pay:[{name:"aa",date:"2020-10-05"},{name:"aa1",date:"2020-10-03"},{name:"aa2",date:"2020-10-04"}]},{name:"b",pay:[{name:"bb",date:"2020-10-10"},{name:"bb1",date:"2020-10-04"},{name:"bb2",date:"2020-10-01"}]}];

const date = new Date("2020-10-05");

const absDate = (rec, date) => Math.min(...
    rec.pay.map(r => Math.abs(new Date(r.date) - date)));

arr.sort((a, b) => absDate(a, date) - absDate(b, date));  
  
console.log(arr);
  

答案 1 :(得分:0)

您可以根据子数组的日期sort来返回子数组,并返回它们的第一个条目以用于父对象的排序。

const arr = [{name:"c",pay:[{name:"c",date:"2020-10-02"},{name:"cc1",date:"2020-10-03"},{name:"cc2",date:"2020-09-28"}]},{name:"a",pay:[{name:"aa",date:"2020-10-05"},{name:"aa1",date:"2020-10-03"},{name:"aa2",date:"2020-10-04"}]},{name:"b",pay:[{name:"bb",date:"2020-10-10"},{name:"bb1",date:"2020-10-04"},{name:"bb2",date:"2020-10-01"}]}];

const date = new Date("2020-10-05");

const getClosestDate = (dates, target) => {
  return dates.map(({date}) => Math.abs(new Date(date) - target)).sort((a, b) => a - b).shift();
}

const sortByDate = (arr, date) => {
  return arr.sort((a, b) => getClosestDate(a.pay, date) - getClosestDate(b.pay, date));
}

const sorted = sortByDate(arr, date);

console.log(sorted);
.as-console-wrapper { max-height: 100% !important; }