Written By: Mohamed Atef
Sorting of Reactjs arrays is the same way to sort Javascript arrays, it's the very simple function we can use anywhere
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'// ]
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 witha - b
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// ]
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;
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.
Join our community and get the chance to solve your code issues & share your opinion with us
Sign up Now