var teamsFirst = [ { name: "Barcelona", country: "Spain" }, { name: "Real Madrid", country: "Spain" }, { name: "MU", country: "England" }, { name: "Totenham", country: "England" } ]; var teamsSecond = [ { name: "Atletico Madrid", country: "Spain" }, { name: "Valencia", country: "Spain" }, { name: "Chelsea", country: "England" }, { name: "Arsenal", country: "England" } ]; var groupA = []; var groupB = []; var groupC = []; var groupD = []; var groups = [ groupA, groupB, groupC, groupD ]; function compareRandom() { return Math.random() - 0.5; } function printTeams() { for ( let i = 0; i < groups.length; i += 1 ) { console.log('Group ' + i + ": " + groups[i][0].name + " and " + groups[i][1].name); } } function checkTeams() { var response = false; for ( var i = 0; i < groups.length; i += 1 ) { if ( groups[i][0].country === groups[i][1].country ) { response = true; } } return response; } function cleanGroups() { groupA = []; groupB = []; groupC = []; groupD = []; } for ( var j = 0; j < 100; j++ ) { teamsFirst.sort(compareRandom); teamsSecond.sort(compareRandom); for ( let i = 0; i < groups.length; i += 1 ) { groups[i].push(teamsFirst[i]); groups[i].push(teamsSecond[i]); } var answer = checkTeams(); if (!answer) { printTeams(); break; } else { cleanGroups(); } } The task of the program is to sort the teams into groups so that in the same group there are no teams from the same country. The problem is this: if the last for replaced with while , then the program will run infinitely, and the commands will never be displayed in the console. But, if for leave, they sometimes appear. How to fix the program so that the teams are sorted, then check (are there any teams in the same group with the same countries), and in the end - output?