Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ixxi's avatar
Level 1

Sorting a vue array alphanumerically

I have an array that looks like this

0 => [
	category => [],
	main_product_codes => [
		[
			'code' => 'SD20',
			'description' => 'a description'
		],
		[
			'code' => 'SD21',
			'description' => 'a description'
		],
		[
			'code' => 'P36',
			'description' => 'a description'
		],
		[
			'code' => 'P37',
			'description' => 'a description'
		],
		[
			'code' => 'P3',
			'description' => 'a description'
		],
		[
			'code' => 'P14',
			'description' => 'a description'
		],
		[
			'code' => 'P6',
			'description' => 'a description'
		],
		[
			'code' => 'EX10',
			'description' => 'a description'
		],
		[
			'code' => 'P18',
			'description' => 'a description'
		],
		[
			'code' => 'P27',
			'description' => 'a description'
		],
		[
			'code' => 'P28',
			'description' => 'a description'
		],
		[
			'code' => 'P30',
			'description' => 'a description'
		],
		[
			'code' => 'P33',
			'description' => 'a description'
		],
		[
			'code' => 'EX11',
			'description' => 'a description'
		]
	]
]

the issue I'm having is that I'm trying to sort this by alphanumerically, but I've only managed to sort it alphabetically

this is what I'm doing to sort my array out

selectProduct(product){
	product['main_product_codes'] = Object.values(product['main_product_codes']).sort(function(a, b){
		if(a.code > b.code) { return 1; }
		if(a.code < b.code) { return -1; }
		return 0;
	});	
}

0 likes
7 replies
martinbean's avatar

@sr57 PHP functions like strcmp tend to only work in PHP, and not JavaScript and Vue.js.

1 like
sr57's avatar

@martinbean

Good return , too quick answer :-), I let you give the function for js.

Tray2's avatar

Where does the data come from?

If it's from your database sort it there. If it's from an external api see if you can pass parameters for sorting.

Ixxi's avatar
Level 1

@Tray2 - the data does come from the database and I had it sorted on the backend, but for some reason when it came to the front end it wasn't sorted

martinbean's avatar
Level 80

@ixxi JavaScript will sort values with whatever algorithm you give it.

If you want to sort alpha-numerical values then you could instead use the localeCompare method that exists on strings:

selectProduct(product) {
	product['main_product_codes'] = Object.values(product['main_product_codes']).sort(function(a, b) {
		return a.code.localeCompare(b.code, 'en', { numeric: true });
	});	
}

This should take into account numbers as well as just alphabetical characters.

Please or to participate in this conversation.