按照特定对象属性值(数字,字符串)进行排序优化
创始人
2024-08-25 12:30:06
0

可以使用JavaScript的Array.sort()方法,配合自定义比较函数,对特定对象属性值进行排序。比较函数返回负值则第一个参数会排在前面,返回正值则第二个参数会排在前面,返回0则两个参数保持原先的顺序不变。示例如下:

const products = [
  { name: 'iPhone 12', price: 999 },
  { name: 'Samsung Galaxy S21', price: 799 },
  { name: 'Google Pixel 5', price: 699 },
  { name: 'OnePlus 9 Pro', price: 969 }
];

// 按照价格从低到高排序
products.sort((a, b) => a.price - b.price);
console.log(products);

// 按照名称进行排序
products.sort((a, b) => {
  const nameA = a.name.toUpperCase();
  const nameB = b.name.toUpperCase();

  if (nameA < nameB) {
    return -1;
  } else if (nameA > nameB) {
    return 1;
  } else {
    return 0;
  }
});
console.log(products);

输出:

[
  { name: 'Google Pixel 5', price: 699 },
  { name: 'Samsung Galaxy S21', price: 799 },
  { name: 'iPhone 12', price: 999 },
  { name: 'OnePlus 9 Pro', price: 969 }
]
[
  { name: 'Google Pixel 5', price: 699 },
  { name: 'iPhone 12', price: 999 },
  { name: 'OnePlus 9 Pro', price: 969 },
  { name: 'Samsung Galaxy S21', price: 799 }
]

相关内容

热门资讯

四分钟辅助!德普之星app安卓... 四分钟辅助!德普之星app安卓版破解版,wepokerplus脚本,项目教程(有挂辅助)1、玩家可以...
2分钟辅助!hhpoker透视... 2分钟辅助!hhpoker透视脚本,wepoker有透视吗,教程书教程(有挂头条)1、超多福利:超高...
第七分钟辅助!wepoker透... 第七分钟辅助!wepoker透视app下载,aa poker辅助包,讲义教程(有挂分享)一、wepo...
第八分钟辅助!wepoker怎... 第八分钟辅助!wepoker怎么开辅助,xpoker辅助器,模块教程(的确有挂)1、不需要AI权限,...
一分钟辅助!wepoker有没... 一分钟辅助!wepoker有没有挂,pokemmo脚本辅助器,讲义教程(有挂教学)1、完成pokem...
第一分钟辅助!hhpoker是... 第一分钟辅助!hhpoker是真的还是假的,wepoker辅助器,阶段教程(有挂技巧)1、金币登录送...
8分钟辅助!hhpoker辅助... 8分钟辅助!hhpoker辅助挂,wejoker私人辅助软件,窍要教程(有挂分析)1、玩家可以在we...
第6分钟辅助!xpoker透视... 第6分钟辅助!xpoker透视辅助,wejoker内置辅助,窍门教程(有挂秘诀)该软件可以轻松地帮助...
第六分钟辅助!aapoker公... 第六分钟辅助!aapoker公共底牌,aapoker怎么设置抽水,办法教程(真是有挂)1、在aapo...
9分钟辅助!wepoker辅助... 9分钟辅助!wepoker辅助真的假的,aapoker透视脚本下载,手册教程(有挂解密)1、首先打开...