How to Sort Data in Ascending or Descending Order in Reactjs

How to sort data in ascending or descending order in Reactjs?

Something like this should be what you're looking for.

import React, { Component } from 'react';
import { render } from 'react-dom';
import products from './products';

class App extends Component {

state = {
products,
prices: [],
}

componentDidMount() {
const { products, prices} = this.state;

prices = products.map(p => p.price.substr(3));
this.setState({ prices })
}

sortAscending = () => {
const { prices } = this.state;
prices.sort((a, b) => a - b)
this.setState({ prices })
}

sortDescending = () => {
const { prices } = this.state;
prices.sort((a, b) => a - b).reverse()
this.setState({ prices })
}

render() {
const { prices } = this.state;
return (
<div>
<ul>
{
prices.map((p, i) => {
return <li>{i} - Rs.{p}</li>;
})
}
</ul>
<button onClick={this.sortAscending}>asc</button>
<button onClick={this.sortDescending}>desc</button>
</div>
);
}
}

render(<App />, document.getElementById('root'));

sort data in table in descending order of date :react js

It is sorted that way because your date format is DD-MM-YYYY
You can sort date if it's in YYY-MM-DD format.

It's a bit hacky but it works in your current codebase.

const sortedOnDate = Object.values(groupedByDate).sort((arr1, arr2) => {

// Convert DD-MM-YYYY into YYYY-MM-DD
const ymdDate1 = arr1[0].date.split("-").reverse().join("-");
const ymdDate2 = arr2[0].date.split("-").reverse().join("-");
if (ymdDate1 < ymdDate2) {
return -1;
} else if (ymdDate1 > ymdDate2) {
return 1;
}
return 0;
});
setData(sortedOnDate);

How to sort data in descending order and show in table, using functional components in React

Let's assume, you have stored your data in state like this:

const [data, setData] = React.useState([])

Then you will create these two functions:

const sortAscending = () => {
let sortedData = data.sort((a, b) => a - b)
setData(sortedData)
}
const sortDescending = () => {
let sortedData = data.sort((a, b) => b - a)
setData(sortedData)
}

Sort the table ascending & descending order when i click on button in reactjs

First, define your state, to save your current sort order:

  state = {
sortedBy: '',
sortDirection: 0
}

Then, define constants, to show the order direction (outside of your class):

const sortAsc = 1;
const sortDesc = -1;

Then, define your sort function:

  sortTable = (columnName) => {
let sortDirection = sortAsc;
if (this.state.columnName === columnName) {
if (this.state.sortDirection === sortAsc) {
sortDirection = sortDesc;
}
}
this.s.TableData.sort((x1, x2) => x1[columnName] < x2[columnName] ? -1 * sortDirection : sortDirection )
this.setState({
columnName, sortDirection, data: this.state.data
})
};

Then, attach this function to each table header:

 <th>
<button type="button" onClick={() => props.sortTable(props.getHeader[0])> // <-- here you pass the header NAME (Upvote, Downvote, Comment and etc.)
{props.getHeader[0]}
</button>
</th>

Keep in mind, that this code is taken out of context, and you may face errors with naming, parameters passing and etc, in general it is a basic abstraction. The sort function was tested out and working. I hope you will manage to integrate it in your application. Good luck!

How to change the sorting order in Antd's table?

I had a look at the antd docs - version 4.19.4 - and sortDirections works in my case.

const CustomTable = () => {
const tableColumns = columns.map((item) => ({ ...item }));

return (
<Table
sortDirections={["descend", "ascend"]}
columns={tableColumns}
dataSource={data}
/>
);
};

Here's a Sandbox: https://codesandbox.io/s/antd-table-sorting-order-9uuv80

I didn't include the tooltip but you can see the order is descending, ascending and none.

Price filtering ascending & descending React js

Try this improved code

 const selectedChangeFilter = (e) => {
const { value } = e.target
if (value === "sporting goods") {
const sportingGoods = data.filter(
(product) => product.category === "Sporting Goods"
);
setProductsInfo(sportingGoods);
}
if (value === "electronics") {
const electronicsGoods = data.filter(
(product) => product.category === "Electronics"
);
setProductsInfo(electronicsGoods);
}
if (value === "lowest price") {
const lowestPriceGoods = data.sort((el1,el2) => el1.price.localeCompare(el2.price, undefined, {numeric: true}));
setProductsInfo([...lowestPriceGoods]);
}
if (value === "highest price") {
const highestPriceGoods = data.sort((el1,el2) => el2.price.localeCompare(el1.price, undefined, {numeric: true}));
setProductsInfo([...highestPriceGoods]);
}
if (value === "all") {
setProductsInfo(data);
}
};


Related Topics



Leave a reply



Submit