对象数组按JavaScript中定义的值列表的列表排序

问题描述 投票:0回答:4

我有类似的对象数组:

[
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "10:00" },
]

和“优先级列表:

[
    "09:00",
    "09:30",
    "12:00" // Yes, it doesn't exist in array of available hours
]

我想要输出该功能:

[
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "10:00" },
]

[我想我可以在JavaScript中将.sort与自己的比较功能一起使用,但我不知道该如何解决这个问题。

对于解决问题的任何提示,我将不胜感激。

javascript sorting
4个回答
0
投票

您可以一键进行排序...优先级列表颠倒可以轻松实现...即,最高优先级具有最高indexOf,列表中未包含的任何优先级都为-1

const data = [
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "10:00" },
]

const priorities = [
    "09:00",
    "09:30",
    "12:00" // Yes, it doesn't exist in array of available hours
];
const reverse = priorities.slice().reverse();

let result = data.sort((a, b) => {
    prioritya = reverse.indexOf(a.hour);
    priorityb = reverse.indexOf(b.hour);
    if (prioritya === priorityb) {
        return a.hour.localeCompare(b.hour);
    }
    return priorityb - prioritya;
});
console.log(result);

0
投票

您可以获取一个索引为priorities的对象,并获取未知属性为Number.MAX_VALUE

var data = [{ hour: "08:00" }, { hour: "08:30" }, { hour: "09:00" }, { hour: "09:30" }, { hour: "10:00" }],
    priorities = ["09:00", "09:30", "12:00"],
    order = priorities.reduce((r, hour, i) => (r[hour] = i + 1, r), {});

data.sort(({ hour: a }, { hour: b }) =>
    (order[a] || Number.MAX_VALUE) - (order[b] || Number.MAX_VALUE));

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

0
投票

检查是否在列表中,如果是,则按该顺序排序,如果不是按小时排序。

var data = [
  { hour: "08:00" },
  { hour: "12:00" },
  { hour: "08:30" },
  { hour: "09:00" },
  { hour: "09:30" },
  { hour: "10:00" },  
]

var priorities = [
  "09:00",
  "09:30",
  "12:00" 
]

var sorted = data.sort (function (a,b) {
  var aH = a.hour
  var bH = b.hour
  var aIndex = priorities.indexOf(aH)
  var bIndex = priorities.indexOf(bH)
  /* if both are priorities sort by index */
  if (aIndex > -1 && bIndex > -1) {
    return aIndex === bIndex ? 0 : aIndex > bIndex ? 1 : -1
  } else if (aIndex > -1) { // if a in priority, move up
    return -1
  } else if (bIndex > -1) { // if b in priority, move up
    return 1
  } else { // if not priorities, sort by string
    return aH.localeCompare(bH)
  }
})

console.log(sorted)

0
投票

[不是像下面这样的简单sort()可以完成这项工作吗?

const arr = [
          { hour: "08:00" },
          { hour: "08:30" },
          { hour: "09:00" },
          { hour: "09:30" },
          { hour: "10:00" },
      ],
      priority = [
          "09:00",
          "09:30",
          "12:00"
      ],
      
      sorted = arr.sort(({hour:hourA},{hour:hourB}) =>
        !priority.includes(hourA) ?
        1 :
        !priority.includes(hourB) ?
        -1 :
        priority.indexOf(hourA) - priority.indexOf(hourB)
      )
      
console.log(sorted)      
© www.soinside.com 2019 - 2024. All rights reserved.