如何对包含数字的数组进行排序?

编程入门 行业动态 更新时间:2024-10-27 08:32:35
本文介绍了如何对包含数字的数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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()

developer.mozilla/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);

更多推荐

如何对包含数字的数组进行排序?

本文发布于:2023-11-30 10:04:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!