user

Mohamed Atef

5 Aug 2022

How to sort arrays in Reactjs?

React js

Sorting of Reactjs arrays is the same way to sort Javascript arrays, it's the very simple function we can use anywhere

ASC sorting in Reactjs

let arr = [
	"O",
	"K",
	"W",
	"M",
	"C",
	"D",
	"B",
	"A",
];
let SortedArray = arr.sort(function(a, b) {
	return a.localeCompare(b);
});
console.log(SortedArray);
//Output
// [
// 'A', 
// 'B', 
// 'C',
// 'D', 
// 'K', 
// 'M',
// 'O', 
// 'W'
// ]

DESC sorting in Reactjs

let arr = [
	"O",
	"K",
	"W",
	"M",
	"C",
	"D",
	"B",
	"A",
];
let SortedArray = arr.sort(function(a, b) {
	return b.localeCompare(a);
});
console.log(SortedArray);
//Output
//[
// 'W', 
// 'O', 
// 'M',
// 'K', 
// 'D', 
// 'C',
// 'B', 
// 'A'
// ]

Note that alphabetical or numerical sorting will be using the same function example but localeCompare is not working with Integer values so we will replace it with a - b

Numerical sorting in Reactjs

let arr = [
	80,
	8,
	4,
	20,
	10,
	60,
	1,
	2,
];
let SortedArray = arr.sort(function(a, b) {
	return a - b;
});
console.log(SortedArray);
//Output
// [
// 1, 
// 2, 
// 4, 
// 8,
// 10,
// 20,
// 60, 
// 80
// ]

Reactjs State array sorting 

import React, { useEffect } from 'react';

const Homepage = () => {

 const [ numbers, serNumbers ] = React.useState(
 [
 1, 
 20,
 2, 
 4, 
 8,
 10,
 60, 
 80
 ]
 );
 
 const sortArray = () => {
 let SortedArray = arr.sort(function(a, b) {
 return a - b;
 });
 serNumbers(SortedArray);
 };
 
 useEffect(() => {
 sortArray();
 }, [sortArray]);
 
 return (
 <div>
 {
 numbers.map((number) => {
 return <p>{number}</p>;
 })
 }
 </div>
 );
};
 
export default Homepage;

Sort array of Objects 

it's gonna be the same function but you can add the object name which will be used as sorting key like the code below 

let arr = [
	{ title: "O", value: 0 },
	{ title: "K", value: 0 },
	{ title: "W", value: 0 },
	{ title: "M", value: 0 },
	{ title: "C", value: 0 },
	{ title: "D", value: 0 },
	{ title: "B", value: 0 },
	{ title: "A", value: 0 },
];
let SortedArray = arr.sort(function(a, b) {
	return a.title.localeCompare(b.title);
});
console.log(SortedArray);
//Output
// [
// 	{ title: 'A', value: 0 },
// 	{ title: 'B', value: 0 },
// 	{ title: 'C', value: 0 },
// 	{ title: 'D', value: 0 },
// 	{ title: 'K', value: 0 },
// 	{ title: 'M', value: 0 },
// 	{ title: 'O', value: 0 },
// 	{ title: 'W', value: 0 }
// ]

That's it, if you have any questions please let me know in the comments below.

Comments

Shilpa

2 Oct 2022

github

Awesome explanation!

© 2024 Copyrights reserved for web-brackets.com