Sorting Single Index Of Array Value In React & JSX
I'm trying to sort rows of a table and change each column given the 'sortBy' value in the state the state is dynamically changing but the function to sort isn't sorting the values
Solution 1:
You can check if the column is a numerical column or a string column using isNaN
. If the column is a number, then simply subtract them. Else use localeCompare
to sort
the rows.
Also, I have added slice
to copy the array since sort
mutates the original array
const columnHeaders = ["Meat", "Protein", "Calories", "Carbohydrates", "Fat"];
const rows = [
["chicken breast", "25", "200", "37", "8"],
["fried chicken", "45", "450", "21", "16"],
["baked fish", "15", "250", "30", "9"]
];
const sortedBy = "Meat", order = "desc";
const newRows = rows.slice().sort((a, b) => {
const valueA = a[columnHeaders.indexOf(sortedBy)];
const valueB = b[columnHeaders.indexOf(sortedBy)];
let sortedValue = 0;
if (!isNaN(valueA) && !isNaN(valueB))
sortedValue = valueA - valueB
else
sortedValue = valueA.localeCompare(valueB)
if (order === "desc") {
sortedValue *= -1;
}
return sortedValue;
})
console.log(newRows)
Post a Comment for "Sorting Single Index Of Array Value In React & JSX"