Answer the question
In order to leave comments, you need to log in
How to display data properly when sorting in React?
Who can tell me how to properly apply my sorting in React. I have a list of data that I get from Firebase books1, they are initially displayed one after another in this format:
{"Name": "Javascript", "Author": "Den", "Year": "2015", "raiting": 5, "ISBN": 67556-5656},
{"Name": "Java", "Author": "Den", "Year": "2017", "raiting": 5, "ISBN": 67556-5656} ,
{"Name": "Linux", "Author": "Den", "Year": "2015", "raiting": 5, "ISBN": 67556-5656},
{"Name": "SQL", "Author": "Den", "Year": "
But I need to sort them first by year, and then in alphabetical order. What I actually did, but in pure JavaScript, but I don’t know how to apply it all correctly now in React.
Here is the successful logic code I wrote in pure JS for sorting by year and alphabetical order of the book, and I want to apply in React
//так скажем основа для дальнейшей структуры
let list_copy = {
books_copy:{
}
}
let db = [
{"Name": "Javascript", "Author": "Den", "Year": "2015", "raiting": 5, "ISBN": 67556-5656},
{"Name": "Java", "Author": "Den", "Year": "2017", "raiting": 5, "ISBN": 67556-5656},
{"Name": "Linux", "Author": "Den", "Year": "2015", "raiting": 5, "ISBN": 67556-5656},
{"Name": "SQL", "Author": "Den", "Year": "2018", "raiting": 5, "ISBN": 67556-5656},
{"Name": "Python", "Author": "Tom", "Year": "2016", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Matlab", "Author": "Mark", "Year": "2014", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Pascal", "Author": "Tom", "Year": "2016", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Excel", "Author": "Mark", "Year": "2018", "raiting": 4, "ISBN": 67556-5656},
{"Name": "C#", "Author": "Leo", "Year": "2017", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Линукс", "Author": "Leo", "Year": "2020", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Виндовс", "Author": "Leo", "Year": "2017", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Книга для новичков", "Author": "Leo", "Year": "2017", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Базовые основы языков", "Author": "David", "Year": "2020", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Грокаем алгоритмы", "Author": "David", "Year": "2015", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Изучаем язык вместе", "Author": "David", "Year": "2020", "raiting": 4, "ISBN": 67556-5656},
{"Name": "Jenkins", "Author": "David", "Year": "2018", "raiting": 4, "ISBN": 67556-5656},
]
let year = [] //массив под года
//сортируем года по возрастанию
function sort(){
for(let i = 0; i < db.length; i++){
db[i].Year = Number(db[i].Year)
}
db.sort((a, b) => a.Year > b.Year ? 1 : -1);
}
sort()
//заносим уникальные года и сортируем их в порядке на увеличение
function year_array(){
for(let i = 0; i < db.length; i++){
year.push(db[i].Year)
}
year = year.filter((item, index) => year.indexOf(item) === index) //удаляем дубликаты
}
year_array()
//добавяем массив с годами
function sort_year(){
for(let i = 0; i < year.length; i++){
list_copy.books_copy[year[i]] = [] //создаем пустой массив под каждый год
}
//сортируем книги по годам
for(let i = 0; i < year.length; i++){
for(let j = 0; j < db.length; j++){
if(db[j].Year == year[i]){
list_copy.books_copy[year[i]].push(db[j])
}
}
}
}
sort_year()
//сортировка по имени
function sort_name(){
for(let j = 0; j < Object.keys(list_copy.books_copy).length; j++){
list_copy.books_copy[year[j]].sort((a, b) => a.Name.localeCompare(b.Name));
}
}
sort_name()
console.log(list_copy.books_copy)
"books_copy":{
"2014":[
{
"Name":"Matlab",
"Author":"Mark",
"Year":2014,
"raiting":4,
"ISBN":61900
}
],
"2015":[
{
"Name":"Грокаем алгоритмы",
"Author":"David",
"Year":2015,
"raiting":4,
"ISBN":61900
},
{
"Name":"Javascript",
"Author":"Den",
"Year":2015,
"raiting":5,
"ISBN":61900
},
{
"Name":"Linux",
"Author":"Den",
"Year":2015,
"raiting":5,
"ISBN":61900
}
],
"2016":[
{
"Name":"Pascal",
"Author":"Tom",
"Year":2016,
"raiting":4,
"ISBN":61900
},
{
"Name":"Python",
"Author":"Tom",
"Year":2016,
"raiting":4,
"ISBN":61900
}
],
"2017":[
{
"Name":"Виндовс",
"Author":"Leo",
"Year":2017,
"raiting":4,
"ISBN":61900
},
{
"Name":"Книга для новичков",
"Author":"Leo",
"Year":2017,
"raiting":4,
"ISBN":61900
},
{
"Name":"C#",
"Author":"Leo",
"Year":2017,
"raiting":4,
"ISBN":61900
},
{
"Name":"Java",
"Author":"Den",
"Year":2017,
"raiting":5,
"ISBN":61900
}
],
"2018":[
{
"Name":"Excel",
"Author":"Mark",
"Year":2018,
"raiting":4,
"ISBN":61900
},
{
"Name":"Jenkins",
"Author":"David",
"Year":2018,
"raiting":4,
"ISBN":61900
},
{
"Name":"SQL",
"Author":"Den",
"Year":2018,
"raiting":5,
"ISBN":61900
}
],
"2020":[
{
"Name":"Базовые основы языков",
"Author":"David",
"Year":2020,
"raiting":4,
"ISBN":61900
},
{
"Name":"Изучаем язык вместе",
"Author":"David",
"Year":2020,
"raiting":4,
"ISBN":61900
},
{
"Name":"Линукс",
"Author":"Leo",
"Year":2020,
"raiting":4,
"ISBN":61900
}
]
}
import React, { useEffect, useState } from 'react'
import firebase from '../../firebase';
import {Link, useHistory} from 'react-router-dom';
const MainPage = () => {
const [books1, setBooks] = useState([])
let history = useHistory();
const ref = firebase.firestore().collection('books1');
const getBooksList = () => {
ref.onSnapshot((querySnapshot)=> {
const list = [];
querySnapshot.forEach((doc)=>{
list.push(doc.data());
});
setBooks(list)
})
};
const deleteBook = (id) => {
ref
.doc(id)
.delete()
.catch((err) =>{
console.error(err);
})
}
const editBook = (id) => {
history.push('/editbook/' + id)
}
useEffect(() => {
getBooksList();
}, [])
let list_copy = {
books_copy:{
}
}
let year = []
//сортируем года по возрастанию
function sort(){
for(let i = 0; i < books1.length; i++){
books1[i].Year = Number(books1[i].Year)
}
books1.sort((a, b) => a.Year > b.Year ? 1 : -1);
}
sort()
//создаем отдельный массив под года
function year_array(){
for(let i = 0; i < books1.length; i++){
year.push(books1[i].Year)
}
year = year.filter((item, index) => year.indexOf(item) === index) //удаляем дубликаты
}
year_array()
function sort_year(){
for(let i = 0; i < year.length; i++){
list_copy.books_copy[year[i]] = []
}
for(let i = 0; i < year.length; i++){
for(let j = 0; j < books1.length; j++){
if(books1[j].Year == year[i]){
list_copy.books_copy[year[i]].push(books1[j])
}
}
}
}
sort_year()
//сортировка по имени
function sort_name(){
for(let j = 0; j < Object.keys(list_copy.books_copy).length; j++){
list_copy.books_copy[year[j]].sort((a, b) => a.Name.localeCompare(b.Name));
}
}
sort_name()
return(
<>
<div>
<p>Test </p>
{list_copy.books_copy.map((c) =>(
<div key={c.id}>
<p>Год: </p>
<div>
<h5>{c.Name}</h5>
<p>Автор: {c.Author}</p>
<p>Год публикации: {c.Year}</p>
<p>Рейтинг: {c.Raiting}</p>
<p>ISBN: {c.ISBN}</p>
<button onClick={() => deleteBook(c.id)}>Удалить</button>
<button onClick={() => editBook(c.id)}>Изменить</button>
</div>
</div>
))}
</div>
</>
)
}
export default MainPage;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question