我们如何用双重条件对 js 对象进行排序

我们如何对这些对象进行从上到下的排序,同时从左到右的排序?

{value: "upperRight"}
{value: "upperLeft"}
{value: "bottomRight"}
{value: "bottomCenter"}
{value: "bottomLeft"}


智慧大石
浏览 51回答 2
2回答

慕后森

split每个valueat/(?=[A-Z])/以获得其垂直和水平位置。这将创建一个像这样的数组:["upper", "Right"]解构数组,将它们变成 2 个独立的变量创建 2 个优先对象。一个用于映射垂直位置的顺序,另一个用于映射水平位置的顺序首先sort根据vertical优先级。如果它们具有相同的优先级,vertical[a1] - vertical[b1]将返回 0。因此,||将根据horizontal部分对它们进行排序const array=[{value:"upperRight"},{value:"upperLeft"},{value:"bottomRight"},{value:"bottomCenter"},{value:"bottomLeft"}];const vertical = {  "upper": 1,  "bottom": 2}const horizontal = {  "Left": 1,  "Center": 2,  "Right": 3}array.sort((a,b) => {  const [a1, a2] = a.value.split(/(?=[A-Z])/)  const [b1, b2] = b.value.split(/(?=[A-Z])/)    return vertical[a1] - vertical[b1] || horizontal[a2] - horizontal[b2]})console.log(array)如果split操作成本较高,您可以添加一个map操作来预先获取所有拆分值并对它们进行排序。

梵蒂冈之花

Array.prototype.sort() 允许您指定比较函数。只需设置一些关于如何对弦乐进行评分的基本规则即可。例如:“上”值10分“底部”得0分“左”得2分“中心”得1分“正确”得0分。在比较函数中将两个分数相减,并将结果用作返回值。var objects = [  { value: 'upperRight' },  { value: 'upperLeft' },  { value: 'bottomRight' },  { value: 'bottomCenter' },  { value: 'bottomLeft' }];function scoreString(s) {  var score = 0;  if (s.indexOf('upper') > -1) score += 20;  if (s.indexOf('Left') > -1) score += 2;  else if (s.indexOf('Center') > -1) score += 1;  return score;}var sorted = objects.sort(function (a, b) {  return scoreString(b.value) - scoreString(a.value);});console.log(sorted);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript