最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

SEO心得admin40浏览0评论
本文介绍了如何对包含数字的数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

发布评论

评论列表(0)

  1. 暂无评论