【问题标题】:How to sort an array of objects with two keys in javascript如何在javascript中使用两个键对对象数组进行排序
【发布时间】:2023-01-19 00:27:18
【问题描述】:

我有一个对象数组,我想根据两个键对它进行排序。

var data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
            {COMPONENT: 'PM', PRIORITY: '0.35'}
            {COMPONENT: 'PM', PRIORITY: ''}]

它应该首先对关键组件(升序)进行排序,然后对优先级进行排序(''应该在数字之前说'0.35')

我试过下面的代码,它只根据键进行排序,即 COMPONENT

data.sort(function (a, b) {
            return (a['COMPONENT'] > b['COMPONENT']) ? 1 : (a['COMPONENT'] < b['COMPONENT']) ? -1 : 0;
        });

我期待以下结果

data = [{COMPONENT: 'PM', PRIORITY: ''}
        {COMPONENT: 'PM', PRIORITY: '0.35'}
        {COMPONENT: 'PM-ABC', PRIORITY: '0.35'}]

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用String#localeCompare

    let data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
                {COMPONENT: 'PM', PRIORITY: '0.35'},
                {COMPONENT: 'PM', PRIORITY: ''}];
    data.sort((a,b) => a.COMPONENT.localeCompare(b.COMPONENT) ||
      a.PRIORITY.localeCompare(b.PRIORITY));
    console.log(data);

    【讨论】:

      【解决方案2】:

      以最基本的方式,无需预先根据某些查询执行排序策略,您可以只进行排序回调,首先考虑属性COMPONENT,当它们不同时,然后属性PRIORITY,最后才考虑平等返回零。

      关键是,如果 COMPONENT 没有差异,则前两个标准通过,第三个成为下一个属性比较。

      var data = [
        {COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
        {COMPONENT: 'PM', PRIORITY: '0.35'},
        {COMPONENT: 'PM', PRIORITY: ''}
      ]
      
      data.sort(function(a, b) {
        if (a.COMPONENT < b.COMPONENT) {
          return -1;
        }
        if (a.COMPONENT > b.COMPONENT) {
          return 1;
        }
        if (a.PRIORITY < b.PRIORITY) {
          return -1;
        }
        if (a.PRIORITY > b.PRIORITY) {
          return 1;
        }
        return 0;
      });
      
      console.log(data);

      【讨论】:

        【解决方案3】:

        您可以按阶段排序,首先是COMPONENT,然后是PRIORITY,并打勾。

        const
            data = [{ COMPONENT: 'PM-ABC', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '' }];
        
        data.sort((a, b) =>
            a.COMPONENT.localeCompare(b.COMPONENT) ||
            (b.PRIORITY === '') - (a.PRIORITY === '')
        );
        
        console.log(data);
        .as-console-wrapper { max-height: 100% !important; top: 0; }

        【讨论】:

          猜你喜欢
          • 2021-02-23
          • 1970-01-01
          • 1970-01-01
          • 2016-12-23
          • 2021-09-22
          • 2013-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多