如何对包含数字的数组进行排序? [英] how to sort array which contains numbers?

查看:113
本文介绍了如何对包含数字的数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数组进行排序.

I am trying to sort an array.

Ex-

let arr = [{label: "Name 5"}, {label: "Name 3"},{label: "Name 12"}, {label: "Name 10"}, {label: "First Name 5"}, {label: "Apple"}, {label: "Orange"}, {label: "water"}];


let sortedArray = arr.sort(function(a, b){
 return a.label.localeCompare(b.label);
});

console.log(sortedArray);

当我尝试对其进行排序时,名称10"首先出现,但名称3"应该首先出现.

When I try to sort it, "Name 10" comes first but "Name 3" should come fist.

我也尝试过-

let sortedArray = arr.sort(function(a, b){
  var nameA=a.label.toLowerCase(), nameB=b.label.toLowerCase();
    if (nameA < nameB){
      return -1;
    } //sort string ascending
    if (nameA > nameB){
      return 1;
    }
   return 0; //no sorting
});

还有-

Array.prototype.reverse()
String.prototype.localeCompare()

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

但是仍然没有运气.谁能指出这里出什么问题了?

But still no luck. Can anyone point out whats wrong here?

推荐答案

为什么不起作用?

您正在对字符串进行排序,默认排序为词典顺序.您正在寻找的是按自然顺序排序.

Why is it not working?

You are sorting strings and the default sorting is lexicographical order. What you are looking for is sorting by natural order.

您可以使用 > String#localeCompare 进行自然排序.

You could use the options of String#localeCompare for natural sorting.

let arr = [{label: "Name 5"}, {label: "Name 3"},{label: "Name 12"}, {label: "Name 10"}, {label: "First Name 5"}, {label: "Apple"}, {label: "Orange"}, {label: "water"}];

arr.sort(function(a, b) {
   return a.label.localeCompare(b.label, undefined, { numeric: true, sensitivity: 'base' });
});

console.log(arr);

这篇关于如何对包含数字的数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆