Javascript:对字符串数字数组进行排序

时间:2018-07-27 14:50:25

标签: javascript arrays

我有一系列如下的学校成绩

(请注意,“ N”代表没有成绩,“ K”代表幼儿园)

  

const toSort = ['1','3','4','5','6','7','9','10','11','12','K' ,'2','N','8'];

我要使用javascript sort()方法排列数组,使其看起来像

  

const sorted = ['K','1','2','3','4','5','6','7','8','9','10' ,'11','12','N'];

这是我的尝试:

ClaimType1: Iif[UCIC_Extract]![ClaimType2]=”PHDA”,[ClaimType1]=”PR”,[ClaimType1]

https://jsbin.com/pocajayala/1/edit?html,js,console,output

有什么办法可以解决这个问题吗?

4 个答案:

答案 0 :(得分:6)

我会这样:

const toSort = ['1', '3', '4', '5', '6', '7', '9', '10', '11', '12', 'K', '2', 'N', '8'];

const transform = k => {
    if (k === 'K') return 0;
    else if (k === 'N') return 13;
    else return +k;
}

const test = toSort.sort((a, b) => transform(a) - transform(b));

console.log(test);

如果您的字母与这些特定数字没有关联,而始终是最大和最小,则可以在Infinity函数上使用-Infinitytransform

const transform = k => {
    if (k === 'K') return -Infinity;
    else if (k === 'N') return Infinity;
    else return +k;
}

答案 1 :(得分:4)

const toSort = ['1', '3', '4', '5', '6', '7', '9', '10', '11', '12', 'K', '2', 'N', '8'];

const test = toSort.sort((a, b) => {
	// console.log('a ' + a + ' b ' + b);
	if (a === "K" || b === "N") {
		return -1;
	}
	if (a === "N" || b === "K") {
		return 1;
	}
	return +a - +b;
});

console.log(test)

答案 2 :(得分:1)

我认为这对您有帮助

const toSort = ['1','3','4','5','6','7','9','10','11','12','K','2','N','8'];

toSort.sort(function(a, b) {
  if(a == 'K') {
    return -1; // always K is smaller
  }
  if(a == 'N')  {
    return 1 // always N is bigger
  }
  if(b == 'K') {
    return 1;
  }
  if(b == 'N')  {
    return -1
  }
  return Number(a) - Number(b);
});

console.log(toSort);

答案 3 :(得分:0)

您可以像这样使用字符串的原生原型 localeCompare 函数:

['1', '3', '4', '5', '6', '7', '9', '10', '11', '12', 'K', '2', 'N', '8']
    .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))

//  ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "K", "N"]

它也适用于其他字符中的数字。