gpt4 book ai didi

Javascript:如何按数字然后字母然后符号对数组进行排序?

转载 作者:搜寻专家 更新时间:2023-11-01 05:19:29 25 4
gpt4 key购买 nike

我正在尝试用 Javascript 对这个数组进行排序

arr = ["ax", "mof", "4", "63", "42", "3", "10", "[", "23", "adidas", "ba", ")", "ABC"]; 

我希望数组显示如下:

["3", "4", "10", "23", "42", "63", "ABC", "adidas", "ax", "ba", "mof", ")", "["]

考虑符号 ")", "["也是。

我想成为数组的顺序是:

  1. 从未成年人到市长的数字
  2. 然后是单词,大小写无所谓。
  3. 最后是符号。

我知道我必须使用 sort(),但问题是我无法用符号对数组进行排序,我遇到了这个问题

我正在使用该代码在 HTML 中显示数组和有序数组

var arr, text, larr, i; 
arr = ["ax", "mof", "4", "63", "42", "3", "10", "[", "23", "adidas", "ba", ")", "ABC"];
larr = arr.length;

text = "<ul>";
for (i = 0; i < larr; i++) {
text += "<li>" + arr[i] + "</li>";
}
text += "</ul>";

document.getElementById("arrayin").innerHTML = text;

console.log(arr);

var arror,textor, larror, j;

arror = arr.sort();

larror = arror.length;

textor = "<ul>";
for (j = 0; j < larror; j++) {
textor += "<li>" + arror[j] + "</li>";
}
textor += "</ul>";

console.log(arror);

document.getElementById("Oarray").innerHTML = textor;

我的最后一个问题是如何用数字、字母和符号对数组进行排序

最佳答案

如您所料,您必须使用排序方法并传入比较函数。为了获得您正在寻找的订单,以下检查将起作用。此处关于 jsfiddle 的完整工作示例 - https://jsfiddle.net/aczhyk8j/1/

function compare(a, b) {
// check for numberhood
const numA = !isNaN(a);
const numB = !isNaN(b);

if (numA && numB) {
return Number(a) - Number(b);
}

if (numA) return -1;
if (numB) return 1;

// check for wordhood
const wordA = /^[a-zA-Z]+$/.test(a);
const wordB = /^[a-zA-Z]+$/.test(b);

if (wordA && wordB) {
return a.localeCompare(b);
}

if (wordA) return -1;
if (wordB) return 1;

return 1; // or whatever logic to sort within non-alphanumeric values
}

// Now, use it in your sort method call.
let arr = ["ax", "mof", "4", "63", "42", "3", "10", "[", "23", "adidas", "ba", ")", "ABC"];

arr.sort(compare);
console.log(arr);

关于Javascript:如何按数字然后字母然后符号对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52765673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com