按属性对对象JavaScript数组进行排序

时间:2018-11-17 06:35:57

标签: javascript sorting object data-structures

我有一个具有2个相关属性的未排序对象数组:typedate。 我需要对这个数组进行排序:

  1. 按日期和
  2. 按类型(每年deposit应该排在withdrawal之前)

以下是输入示例:

let i = [
    {
        date:'2017',
        type:'withdrawal',
        amount:-5
    },
    {
        date:'2016',
        type:'deposit',
        amount:12
    },
    {
        date:'2018',
        type:'deposit',
        amount:54
    },
    {
        date:'2017',
        type:'deposit',
        amount:20
    },
    {
        date:'2016',
        type:'withdrawal',
        amount:55
    },
    {
        date:'2018',
        type:'withdrawal',
        amount:54
    }
]  

目标是输出如下内容:

let o = [
    {
        date:'2016',
        type:'deposit',
        amount:12
    },
    {
        date:'2016',
        type:'withdrawal',
        amount:55
    },
    {
        date:'2017',
        type:'deposit',
        amount:20
    },
    {
        date:'2017',
        type:'withdrawal',
        amount:-5
    },
    {
        date:'2018',
        type:'deposit',
        amount:54
    },
    {
        date:'2018',
        type:'withdrawal',
        amount:54
    }
]

到目前为止,我设法使用以下方法按日期对数组进行排序:

o = i.sort((a,b)=>(a.date - b.date))

但是我找不到一种按类型对其进行排序的方法

3 个答案:

答案 0 :(得分:3)

您可以使用如下所示的“排序”。通过使用“ localeCompare”,它将按升序对“类型”进行排序-“存款”将在“提款”之前,因为“ d”在“ w”之前

就是用这个-

i.sort((a,b) => ((+a.date) - (+b.date) || (a.type.localeCompare(b.type))))
  • 您首先按“日期”排序,如果日期相同,则它会处于“或”条件(因为a.date-b.date将为0)以检查“类型”

let i = [
    {
        date:'2017',
        type:'withdrawal',
        amount:-5
    },
    {
        date:'2016',
        type:'deposit',
        amount:12
    },
    {
        date:'2018',
        type:'deposit',
        amount:54
    },
    {
        date:'2017',
        type:'deposit',
        amount:20
    },
    {
        date:'2016',
        type:'withdrawal',
        amount:55
    },
    {
        date:'2018',
        type:'withdrawal',
        amount:54
    }
]  

i.sort((a,b) => ((+a.date) - (+b.date) || (a.type.localeCompare(b.type))))

console.log(i)

答案 1 :(得分:0)

您可以使用string#localCompare首先根据date对数组进行排序,然后再根据type对数组进行排序。

let arr = [ { date:'2017', type:'withdrawal', amount:-5 }, { date:'2016', type:'deposit', amount:12 }, { date:'2018', type:'deposit', amount:54 }, { date:'2017', type:'deposit', amount:20 }, { date:'2016', type:'withdrawal', amount:55 }, { date:'2018',type:'withdrawal', amount:54 } ];
arr.sort((a,b) => a.date.localeCompare(b.date) || a.type.localeCompare(b.type));
console.log(arr);

答案 2 :(得分:0)

虽然可能不是最理想的解决方案,但我在Array.prototype.sort方法中将类型作为字符串“ a”和“ b”连接到日期上,然后基于该字符串对数组进行排序。 / p>

i.sort((a,b) => {
  let aStr = `${a.date}${a.type}`;
  let bStr = `${b.date}${b.type}`;
  if(aStr > bStr) {
    return 1;
  } else if(aStr === bStr) {
    return 0;
  } else {
    return -1;
  }
});

希望有帮助!