展开并重新排序对象数组

时间:2017-11-02 14:19:54

标签: javascript arrays reactjs sorting data-structures

我有和数组

    reservation1:[
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
    ]

我需要将数组扩展为9 并使用名称为null active false dayindex的对象填充它:按顺序在0到10之间 所需的输出是

  output =[
   {name:"",active:false,dayindex:0}
   {name:"8:30",active:true,dayindex:1}

    ...

我试着用它来扩展

它适用于扩展,但我无法按照我想要的重新排序

1 个答案:

答案 0 :(得分:1)

您可以在添加其他元素后对数组进行排序:



var reservation = [
    {name:"8:30",active:true,dayindex:1},
    {name:"jad",active:true,dayindex:3},
    {name:"tony",active:true,dayindex:4},
    {name:"",active:false,dayindex:6}
];
var availabeDayIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].filter(el => !reservation.map(it => it.dayindex).includes(el));
var sortField = 'dayindex';
reservation = [...reservation, ...Array.from(Array(9 - reservation.length), (val, key) => ({name: null, active: false, dayindex: availabeDayIndex[key]}))].sort((a, b) => a[sortField] - b[sortField]);
console.log(reservation);