为了账号安全,请及时绑定邮箱和手机立即绑定

JS:按两个不同的属性对 JSON 数组进行排序,保持数组中指定的顺序

JS:按两个不同的属性对 JSON 数组进行排序,保持数组中指定的顺序

紫衣仙女 2021-10-14 10:08:40
我有一组需要排序的 JSON 对象。数组需要按两个不同的属性排序。首先,数组应按found属性按字母顺序排序。其次,应该对数组进行排序,以便website属性按照 中指定的相同顺序下降siteOrder。var siteOrder = ['facebook', 'twitter', 'reddit', 'youtube', 'instagram'];var data = [    {found: 'booker', website: 'reddit'},    {found: 'john', website: 'facebook'},    {found: 'walter', website: 'twitter'},    {found: 'smith', website: 'instagram'},    {found: 'steve', website: 'youtube'},    {found: 'smith', website: 'facebook'},    {found: 'steve', website: 'twitter'},    {found: 'john', website: 'instagram'},    {found: 'walter', website: 'youtube'}];/* Example output: Sorted output by found, respecting the order of the websites specified{found: 'booker', website: 'reddit'},{found: 'john', website: 'facebook'},{found: 'john', website: 'instagram'},{found: 'smith', website: 'facebook'},{found: 'smith', website: 'instagram'},{found: 'steve', website: 'twitter'},{found: 'steve', website: 'youtube'},{found: 'walter', website: 'twitter'},{found: 'walter', website: 'youtube'}*/我可以使用以下方法按找到的属性按字母顺序排序:data.sort(function(a, b) {    var textA = a.found.toUpperCase();    var textB = b.found.toUpperCase();    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;});但是我不知道如何使它也遵守网站的指定顺序。
查看完整描述

3 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

如果找到的 2 个对象的文本相同,则比较 siteOrder 中 2 个对象的网站索引。


data.sort(function (a, b) {

  var textA = a.found.toUpperCase();

  var textB = b.found.toUpperCase();

  var foundOrder = (textA < textB) ? -1 : (textA > textB) ? 1 : 0;

  if (foundOrder === 0) {

    var indexA = siteOrder.indexOf(a.website);

    var indexB = siteOrder.indexOf(b.website);

    return (indexA < indexB) ? -1 : (indexA > indexB) ? 1 : 0;

  }

  return foundOrder;

});


查看完整回答
反对 回复 2021-10-14
  • 3 回答
  • 0 关注
  • 365 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信