javascript - JS 下划线 : array of dicts in pairs

标签 javascript arrays sorting underscore.js

是否可以对如下所示的数组进行排序:

array = [ 
    {'title': 'a',
      'text': 'info a1'},
    {'title': 'b',
      'text': 'info b1'},
    {'title': 'c',
      'text': 'info c1'},
    {'title': 'a',
      'text': 'info a2'},
    {'title': 'a',
      'text': 'info a3'},
    {'title': 'b',
      'text': 'info b2'}
]

按对排序 - 即 - 将所有不必要的字典传递到数组末尾 喜欢这个:

array = [ 
    {'title': 'a',
      'text': 'info a1'},
    {'title': 'a',
      'text': 'info a2'},
    {'title': 'b',
      'text': 'info b1'},
    {'title': 'b',
      'text': 'info b2'},
    {'title': 'a',
      'text': 'info a3'},
    {'title': 'c',
      'text': 'info c1'}
]

如果有帮助的话我也使用下划线。该数组还包含其他数据。我需要显示所有成对的元素。以及列表末尾没有配对的所有元素。我认为如果在显示之前对数组进行排序会更容易。

知道如何做到这一点吗?

最佳答案

也许您考虑使用 necessary 标志,然后您可以将 necessary 的真值排序到顶部,然后按 title 排序。

var array =[
        { title: 'a', text: 'info a1', necessary: true },
        { title: 'b', text: 'info b1', necessary: true },
        { title: 'c', text: 'info c1', necessary: false },
        { title: 'a', text: 'info a2', necessary: true },
        { title: 'a', text: 'info a3', necessary: false },
        { title: 'b', text: 'info b2', necessary: true }
    ];

array.sort(function (a, b) {
    return b.necessary - a.necessary || a.title > b.title || -(a.title < b.title);
});

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

关于javascript - JS 下划线 : array of dicts in pairs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015812/

相关文章:

javascript - 创建一组带有与 JavaScript 关联的点击事件的复选框

java - Collections.shuffle 没有按预期工作

c - 如何在 C 中对链表进行排序?

php - 按 WP_Query 中的自定义 Woocommerce 产品排序排序

bash - 在同一行 Bash 上排序

javascript - 如何让 Knockout JS 和 ClipboardJS 一起工作?

php - 如何通过ajax将值传递给php变量

javascript - 如何将 "Disabled"属性添加到 Ember.Select 中的选项

php - 列出并展开

javascript - 简单的 Javascript 游戏 : Possible object array error