Text : Working with Sort and Filter Functions

 sort()
    - sorts the elements of an array in place and returns the reference to the same array, now sorted

syntax:
    const sortedList = [...myList, {name:name, balance:balance}];
//by name
    sortedList.sort((a, b) => a.name.localeCompare(b.name))
//by balance
    sortedList.sort((a, b) => a.balance - b.balance)
    setMyList(sortedList);


filter()
    - creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

syntax:
    let filteredList  = [...studentsList, {name:name, balance:balance}];

    filteredList = filteredList.filter(student => {
      return student.balance > 2000;
    })

    setMyList(filtered);

 

Working code as seen in the video:

"use client";

import { useEffect, useState } from "react";

const Home = () => {
  const [myList, setMyList] = useState([]);
  const [stud_name, setName] = useState("");
  const [stud_balance, setBalance] = useState(0);
  const [totalBalance, setTotalBalance] = useState(0 );

  const fillList = () => {
    setMyList([
      { name: "Makyus", balance: 10000 },
      { name: "Razzie", balance: 5000 },
      { name: "LaNay", balance: 3000 },
    ]);
  };

  const addToList = () => {
    // const sortedList = [...myList, {name: stud_name, balance:stud_balance}];
    // //sort by name
    // //sortedList.sort((a, b) => a.name.localeCompare(b.name));
    // //sorted by balance
    // sortedList.sort((a, b) => a.balance - b.balance);
    // setMyList(sortedList);

    let filteredList  = [...myList, {name: stud_name, balance:stud_balance}];
    filteredList = filteredList.filter(student => {
      return student.balance > 2000;
    });

    setMyList(filteredList);
  };

  const getTotalBalance = () => {
    // var total = 0;
    // myList.forEach(student => {
    //   total += parseFloat(student.balance);
    // })
    // return total;
    return myList.reduce((acc, student)=> acc + parseFloat(student.balance), 0);
  }

  //initial render
  useEffect(() => {
    fillList();
  }, []);

  //when myList changes size
  useEffect(() => {
    setTotalBalance(getTotalBalance());
  }, [myList])

  return (
    <>
      <h1>Working with Lists and useEffect() Hook</h1>

      <input
        type="text"
        placeholder="Enter a name"
        value={stud_name}
        onChange={(e) => {
          setName(e.target.value);
        }}
      />
      <input
        type="number"
        placeholder="Enter balance"
        value={stud_balance}
        onChange={(e) => {
          setBalance(e.target.value);
        }}
      />
      <button onClick={addToList}>Add To List</button>

      {/* <ul>
      {
        myList.map((student) => {
          return(
            <li>{student}</li>
          );
        })
      }
    </ul> */}
      <table>
        <tbody>
          {myList.map((student, index) => {
            return (
              <tr key={index}>
                <td style={{ border: "1px solid #000" }}>{student.name}</td>
                <td style={{ border: "1px solid #000" }}>{student.balance}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <h3>Total Balance - {totalBalance}</h3>
    </>
  );
};

export default Home;


No comments:

Post a Comment

IMAGE : OPTIMIZING API END POINTS USING CLASSES IN PHP

 BACK END users.php   TEXT VERSION connection.php   TEXT VERSION FRONT END main.dart (LOGIN PAGE) register.dart   TEXT VERSION