Чтобы уменьшить массив до нескольких его элементов, я бы почти всегда предлагал использовать Array.filter()
, однако на самом деле я собираюсь сначала представить альтернативное решение в вашем случае.
Если бы вы использовали filter
для циклического перемещения по элементам и поиска нужных вам элементов, а затем с помощью цикла for
для добавления их в таблицу, вы бы просматривали некоторые изодни и те же элементы дважды.
Вместо этого мы можем применить нашу логику, чтобы пропустить игры, которые нам не нужны внутри одного и того же цикла , выполнив что-то вроде этого:
//If "team" is neither the away team, nor the home team, skip this game
if (![game.awayTeam, game.homeTeam].includes(team)) return;
Пример 1: (комментарии добавлены)
var data = { Schedule: [{ awayTeam: "Jets", homeTeam: "Bills", winner: "Bills", week: 1 }, { awayTeam: "Saints", homeTeam: "Cardinals", winner: "Cardinals", week: 1 }, { awayTeam: "Giants", homeTeam: "Bengals", winner: "Bengals", week: 2 }, { awayTeam: "Bills", homeTeam: "Jaguars", winner: "Bills", week: 2 }, { awayTeam: "Bills", homeTeam: "Patriots", winner: "Patriots", week: 3 } ] };
function setScheduleByTeam(team) {
let schedule = data["Schedule"]; //Get the schedule
var $outputTable = $("#output"); //Store the table as a variable
$outputTable.find("tbody").empty(); //Empty out the current records
schedule.forEach(function(game) { //For each game in the schedule
if (![game.awayTeam, game.homeTeam].includes(team)) return; //Skip the record if our team isn't in it
//Create + Append table row
var tableRow = "<tr><td>" + game.week + "</td><td>" + game.homeTeam + "</td><td>" + game.awayTeam + "</td><td>" + game.winner + "</td></tr>";
$outputTable.append(tableRow);
});
}
//On button click
$("body").on("click", "button", function() {
let team = $('#teamSelect').val(); //Get selected team
setScheduleByTeam(team); //Update the table to that team's schedule
});
td,th { padding: 5px 15px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="teamSelect">
<option>Select Team</option>
<option value="Bengals">Bengals</option>
<option value="Bills">Bills</option>
<option value="Jets">Jets</option>
</select>
<button>Go!</button>
<table id="output">
<thead>
<tr>
<th>Week</th>
<th>Home</th>
<th>Away</th>
<th>Winner</th>
</tr>
</thead>
</table>
Однако некоторые могут поспорить за чистоту, и в этом случае я бы предложил использовать метод filter
, который я упоминал ранее:
Пример 2 (Комментарии добавлены)
var data = { Schedule: [{ awayTeam: "Jets", homeTeam: "Bills", winner: "Bills", week: 1 }, { awayTeam: "Saints", homeTeam: "Cardinals", winner: "Cardinals", week: 1 }, { awayTeam: "Giants", homeTeam: "Bengals", winner: "Bengals", week: 2 }, { awayTeam: "Bills", homeTeam: "Jaguars", winner: "Bills", week: 2 }, { awayTeam: "Bills", homeTeam: "Patriots", winner: "Patriots", week: 3 } ] };
//Filter out schedule to only games where awayTeam == team OR homeTeam == team.
//Returns the filtered team's schedule
const getGamesByTeam = (team) => data.Schedule.filter(g => g.awayTeam == team || g.homeTeam == team);
function updateScheduleTable(games) {
var $outputTable = $("#output"); //Store table as variable
$outputTable.find("tbody").empty(); //Remove existing rows
games.forEach(function(game) { //For each game, append to table
var tableRow = "<tr><td>" + game.week + "</td><td>" + game.homeTeam + "</td><td>" + game.awayTeam + "</td><td>" + game.winner + "</td></tr>";
$outputTable.append(tableRow);
});
}
$("body").on("click", "button", function() {
let team = $('#teamSelect').val(); //Get the selected team
let games = getGamesByTeam(team); //Get a filtered array of one team's schedule
updateScheduleTable(games); //Update the table based on that set of games
});
td,th { padding: 5px 15px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="teamSelect">
<option>Select Team</option>
<option value="Bengals">Bengals</option>
<option value="Bills">Bills</option>
<option value="Jets">Jets</option>
</select>
<button>Go!</button>
<table id="output">
<thead>
<tr>
<th>Week</th>
<th>Home</th>
<th>Away</th>
<th>Winner</th>
</tr>
</thead>
</table>