通过属性(自定义顺序,而不是字母顺序)对对象数组进行排序。

4

我希望你能帮我解决这个小问题。

我想根据代码值对该数组进行排序,但不按字母顺序排列。我已经在加粗指定了这一点,但最终还是被标记了,人们甚至不关心阅读问题

例如,我想先有所有的绿色物品,然后是所有的蓝色物品,最后是所有的红色物品。最好的方法是什么?

[
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
]

使用sort函数是否可以实现这个功能?在这种情况下条件是什么?


@JasperSeinhorst 我刚刚遍历了数组,我想知道是否有更快的方法。 - Luca De Nardi
@lilezek请在标记之前阅读问题,我不想按字母顺序排列 - Luca De Nardi
1
@LucaDeNardi 你只需要自己编写排序函数,就是这么简单。 - lilezek
@lilezek这并不完全正确,因为有人提供了更快的方法来做到这一点。 - Luca De Nardi
1
@LucaDeNardi 这里的每个人都提供了一个排序函数。 - lilezek
7个回答

19

您可以为所需的订单取一个对象。

var array = [{ code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3 };
    
array.sort(function (a, b) {
    return order[a.code] - order[b.code];
});

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

对于未知颜色/值,您可以使用默认值:

  • 0,如果需要将其排序到顶部或
  • Infinity 或者某些人建议使用此值,因为它具有计算Number.MAX_VALUE的能力,可以用于将其排序到底部,
  • 或使用任何其他值用于在其他组之间进行排序。

最后,您可以使用另一个排序部分和逻辑 OR 运算符 ||链接来排序特殊处理的项目。

var array = [{ code: "YELLOW", value: 0 }, { code: "BLACK", value: 0 }, { code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3, default: Infinity };
    
array.sort(function (a, b) {
    return (order[a.code] || order.default) - (order[b.code] || order.default) || a.code.localeCompare(b.code);
});

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


1
嗯,这很有趣!我没有考虑使用对象来跟踪订单 :) - Luca De Nardi

3

首先设置自定义优先级

var codePriority = [ "GREEN", "BLUE", "RED" ];

现在在排序中使用相同的方式:
arr.sort( function(a,b){ 
   if ( a.code == b.code ) return a.value - b.value;
   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) ; notice this line
})

演示

var arr = [
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
];
var codePriority = [ "GREEN", "BLUE", "RED" ];
arr.sort( function(a,b){ 
   if ( a.code == b.code ) return a.value - b.value;
   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code )
});
console.log( arr );


您可以删除if检查。尝试使用return codePriority.indexOf(a.code) - codePriority.indexOf(b.code) || a.value - b.value - Rajesh
@Rajesh 哦,没想到那个 :)... 我现在会保持原样,这样更易读。 - gurvinder372

1
您可以使用排序函数,例如 Array.prototype.sort()。访问 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
首先,您需要决定是按升序还是降序进行排序。要按升序排序,可以像这样操作:
arr.sort((a, b) => {
    return a.color < b.color ? -1 : a.color > b.color ? 1 : 0;
  });

按降序执行:

arr.sort((a, b) => {
    return a.color > b.color ? -1 : a.color < b.color ? 1 : 0;
  });

现在假设你想要某个特定的颜色排在最前面并显示出来。你可以编写以下函数:

const sortByKeyAsc = (arr,color) =>
  arr.sort((a, b) => {
    if(a.color < b.color || (a.color === color && b.color !== color)){
      return -1;
    }
    if(a.color > b.color || (a.color !== color && b.color === color)){
      return 1
    }
    return 0;
  });

你可以像这样使用它:

const array1 = sortByKeyAsc(arr,'pink');

1

这是一个按照特定颜色排序的函数。

const colors = [{
    name: "T-shirt",
    color: "red",
    price: 20
  },
  {
    name: "Shoes",
    color: "yellow",
    price: 20
  },
  {
    name: "Pants",
    color: "red",
    price: 20
  },
  {
    name: "Cap",
    color: "yellow",
    price: 20
  },
  {
    name: "Skirt",
    color: "red",
    price: 15
  },
]

let sortByColor = color => colors.sort((a, b) => a.color === color ? -1 : 1)

console.log(sortByColor('red'))


1
你可以实现一个模式数组,并根据该模式数组中元素的索引进行排序。

const a = ['GREEN', 'BLUE', 'RED'];

const o = [{code:"RED",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0}];

const r = o.slice().sort(({ code: q }, { code: w }) => a.indexOf(q) - a.indexOf(w));

console.log(r);


0

你可以使用这个函数按字母顺序对颜色进行排序

  var sortedArr = arr.sort((first, second)=>{
            
        return first.color < second.color ? -1 : 1
    })

0

我曾经遇到一个情况,需要匹配字符串状态并按照不同的状态进行排序。最终发现使用.findIndex.includes是最好的方法。

statusPriority设置了预期的顺序。一旦找到索引,就可以进行比较并返回给.sort函数。

let records = [
  {status: 'Record is ready to submit.', active: true, name: 'A'},
  {status: 'Record has been sent.', active: true, name: 'B'},
  {status: 'Activation is required.', active: true, name: 'C'},
  {status: 'Record submission failed.', active: true, name: 'D'},
  {status: 'Creation is pending.', active: true, name: 'E'},
]

console.log(records.map(r => r.status))

let statusPriority = ['creation', 'activation', 'sent', 'ready', 'failed'];
records.sort((a, b) => {
  let aIndex = statusPriority.findIndex(status => a.status.toLowerCase().includes(status));
  let bIndex = statusPriority.findIndex(status => b.status.toLowerCase().includes(status));
  return aIndex - bIndex;
})

console.log(records.map(r => r.status))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接