RyeGuy
RyeGuy

Reputation: 4483

JavaScript: Sort an array of String numbers

I have an array of school grades that looks like the following.

(Note 'N' stands for no grades and 'K' stands for kindergarten)

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

Using the JavaScript sort() method, I would like to arrange the array so it will look like:

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

Here is my attempt at it:

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

toSort.sort();
// Produces: ["1", "10", "11", "12", "2", "3", "4", "5", "6", "7", "8", "9", "K", "N"]

const test = toSort.sort((a, b) => {
  if (a === 'K') {
    return -1;
  }

  return Number(a) < Number(b) ? -1 : Number(a) > Number(b) ? 1 : 0;
});

console.log(test)

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

How I can resolve this?

Upvotes: 14

Views: 21862

Answers (4)

Liviu
Liviu

Reputation: 319

You can use the string's native prototype localeCompare() function like so:

['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"]

It works well with numbers among other characters too.

Upvotes: 22

Aramil Rey
Aramil Rey

Reputation: 3475

I would do it like this:

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

In case your letters don't have correlation with those specific numbers, and instead are always the biggest and the smallest, you can use Infinity and -Infinity on the transform function.

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

Upvotes: 6

Saeed
Saeed

Reputation: 5488

I think this helps you

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

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

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)

Upvotes: 7

Related Questions