根据多个条件对数组进行排序

时间:2019-12-16 20:05:51

标签: javascript arrays sorting

我有一个未排序的数组和一个错误数组


const arr = [
    {id: "BLR_123"},
    {id: "BLR_122"},
    {id: "BLR_125"},
    {id: "BLR_121"},
    {id: "BLR_126"},
    {id: "BLR_124"},
    {id: "BLR_127"},
    {id: "BLR_128"}
]

const errors = ['BLR_123', 'BLR_124', 'BLR_125']

const sortedArr = arr.sort((a, b) => {
  if (a.id < b.id) {
    return -1;
  }
  if (a.id > b.id) {
    return 1;
  }
  return 0;
})

console.log(sortedArr.map(({id}) => id))

我要根据2个条件对其进行排序

  1. 当id错误时,将其放在顶部
  2. 不存在id时,将根据字母进行排序

最终结果必须是关于数据集的。

const arr = [
    {id: "BLR_123"},
    {id: "BLR_122"},
    {id: "BLR_125"},
    {id: "BLR_121"},
    {id: "BLR_126"},
    {id: "BLR_124"},
    {id: "BLR_127"},
    {id: "BLR_128"}
]

const errors = ['BLR_123', 'BLR_124', 'BLR_125']

const sortedArr = arr.sort((a, b) => {
  if (a.id < b.id) {
    return -1;
  }
  if (a.id > b.id) {
    return 1;
  }
  return 0;
})

console.log(sortedArr.map(({id}) => id))

是否可以使用单一排序功能?

1 个答案:

答案 0 :(得分:1)

您需要检查a.idb.id是否存在错误。如果两者都存在错误,或者都不存在错误,请使用String.localeCompare()按字母顺序排序。如果只有一个错误存在,则返回1或-1:

const arr = [{"id":"BLR_123"},{"id":"BLR_122"},{"id":"BLR_125"},{"id":"BLR_121"},{"id":"BLR_126"},{"id":"BLR_124"},{"id":"BLR_127"},{"id":"BLR_128"}]

const errors = ['BLR_123', 'BLR_124', 'BLR_125']

const sortedArr = arr.sort((a, b) => {
  const aInErrors = errors.includes(a.id)
  const bInErrors = errors.includes(b.id)
  
  // if both are in error or both are not in errors
  if((aInErrors && bInErrors) || (!aInErrors && !bInErrors)) {
    return a.id.localeCompare(b.id) // sort alphabetically
  }
  
  if(aInErrors) return -1
  
  return 1
})

console.log(sortedArr.map(({id}) => id))