You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于ES2020实现JavaScript对象按员工数属性值排序的最优方案

方案说明

你当前的实现逻辑是没问题的,排序后返回数组本身是非常实用的结构,数组的原生遍历、切片、过滤方法都比对象更适合处理排序后的有序数据。如果你需要保留对象的访问形式,ES6+ 标准中字符串类型的对象键会严格按照插入顺序存储,我们可以把排序后的数组转回对象,也可以优化原有函数的写法更符合现代JS语法。

针对按员工数量排序的快速实现

如果只需要针对当前场景排序,不需要通用功能,可以用更简洁的写法:

// reverse为true时返回降序结果,默认升序
const sortByEmployees = (companies, reverse = false) => {
  return Object.fromEntries(
    Object.entries(companies).sort(([,a], [,b]) => {
      const diff = a.employees - b.employees
      return reverse ? -diff : diff
    })
  )
}

// 调用示例
const sortedCompanies = sortByEmployees(companies) // 升序对象
const sortedCompaniesDesc = sortByEmployees(companies, true) // 降序对象

优化后的通用排序函数

对原有通用函数做了以下优化:

  • 用Object.entries替代for...in+hasOwnProperty判断,代码更简洁,天然过滤继承属性
  • 用解构参数替代零散参数传值,配置更直观
  • 支持选择返回数组或者对象,适配不同场景
  • 字符串排序改用localeCompare方法,处理特殊字符更稳定
function sortProperties(obj, sortedBy, options = {}) {
  const {
    isNumericSort = false,
    reverse = false,
    returnType = 'array' // 可选值:'array' | 'object'
  } = options

  const reverseMulti = reverse ? -1 : 1
  const sortList = Object.entries(obj)

  sortList.sort(([, a], [, b]) => {
    if (isNumericSort) {
      return reverseMulti * (a[sortedBy] - b[sortedBy])
    }
    const x = String(a[sortedBy]).toLowerCase()
    const y = String(b[sortedBy]).toLowerCase()
    return reverseMulti * x.localeCompare(y)
  })

  return returnType === 'object' ? Object.fromEntries(sortList) : sortList
}

// 按员工数量排序调用示例
// 返回数组
const sortedArr = sortProperties(companies, 'employees', {
  isNumericSort: true,
  reverse: false
})
// 返回对象
const sortedObj = sortProperties(companies, 'employees', {
  isNumericSort: true,
  reverse: false,
  returnType: 'object'
})

兼容提示

如果运行环境不支持ES2019的Object.fromEntries,可以用reduce方法手动把排序后的数组转为对象:

const sortedObj = sortList.reduce((res, [key, value]) => {
  res[key] = value
  return res
}, {})

内容的提问来源于stack exchange,提问作者Muthamizhchelvan. V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:48:01