Skip to content
Advertisement

If statement won’t work, but the ternary will. Why?

I was wondering why the const sortingMethod that is commented out doesn’t work, and the sortingMethod that is active does work.

The first one is a ‘normal’ if-statement while the other is a ternary operator, if I’m not mistaken. Isn’t it that same thing, but written differently?

import { useState } from "react";

import Player from "./Player";

export default function Scoreboard() {
  const initPlayerScores = [
    {
      id: 1,
      name: "Dexter",
      score: 33,
    },
    {
      id: 2,
      name: "Noodles",
      score: 112,
    },
    {
      id: 3,
      name: "Greg",
      score: 3,
    },
    {
      id: 4,
      name: "Ron",
      score: 12,
    },
  ];

  const [players, setPlayers] = useState(initPlayerScores);

  const [sortBy, setSortBy] = useState("score");

  const sortByScore = (playerA, playerB) => playerA.score - playerB.score;

  const sortByName = (playerA, playerB) =>
    playerA.name.localeCompare(playerB.name);

  // const sortingMethod = () => {
  //   if (sortBy === "name") {
  //     return sortByName;
  //   } else {
  //     return sortByScore;
  //   }
  // };

  const sortingMethod = sortBy === "name" ? sortByName : sortByScore;

  const playersSorted = [...players].sort(sortingMethod);

  const changeSorting = (event) => {
    setSortBy(event.target.value);
  };

  return (
    <div>
      <h1>The Scoreboard</h1>
      Sort by{" "}
      <select onChange={changeSorting}>
        <option value="name">Name</option>
        <option value="score">Score</option>
      </select>
      {playersSorted.map((player) => (
        <Player key={player.id} name={player.name} score={player.score} />
      ))}
    </div>
  );
}

Advertisement

Answer

I think what @deceze means is that you need to evaluate your sortByName and sortByScore functions in sortingMethod. The code below will work:

const sortingMethod = (playerA, playerB) => {
    if (sortBy === "name") {
        return sortByName(playerA, playerB);
    } else {
        return sortByScore(playerA, playerB);
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement