美文网首页ES6
js中对对象数组进行字符串排序

js中对对象数组进行字符串排序

作者: Frank_Fang | 来源:发表于2022-08-18 18:34 被阅读0次
    const arr = [
      { name: 'Jesus' },
      { name: 'Peter' },
      { name: 'Andrew' },
      { name: 'John' }
    ]
    // 对对象数组进行字符串排序
    arr.sort((a, b) => {
      const x = a.name.toLowerCase()
      const y = b.name.toLowerCase()
      if (x < y) { return -1 }
      if (x > y) { return 1 }
      return 0
    })
    console.log(arr) // [{name: 'Andrew'}, {name: 'Jesus'}, {name: 'John'}, {name: 'Peter'}]

相关文章

网友评论

    本文标题:js中对对象数组进行字符串排序

    本文链接:https://www.haomeiwen.com/subject/bpoegrtx.html