Is there a way to iterate through an array of objects and eliminate duplicate names to retrieve distinct players in a fresh array?

I'm struggling to filter out duplicate player names from an array of objects and create a new array with only unique player names in the same order. I have considered using a forEach loop or a similar approach, but I am unsure of how to handle multiple occurrences.

const players = function(outcomes) {

  const arr = [];
  for (let i = 0; i < outcomes.length; i++) {
    if (outcomes.includes(winner, loser))
    arr.push(arr[i]);
  }
  return arr;

};

For example:

const playerNames = [
 { winner: 'Sam',   loser: 'Bruce',    loser_points: 10 },
  { winner: 'Sam',   loser: 'Hakim',  loser_points: 9 }]

Expected Output: [Sam, Bruce, Hakim]

Answer №1

let gameParticipants = [
    { winner: 'Sam',   loser: 'Bruce',    loser_points: 10 },
    { winner: 'Sam',   loser: 'Hakim',  loser_points: 9 }
];

const findPlayers = function(participants) { 
    let players = {}; 
    let participant;
    for (let i=0; i<participants.length; i++) {
        participant = participants[i];
        players[participant.winner] = 1;
        players[participant.loser] = 1;
    }
    return Object.keys(players);
}

console.log(findPlayers(gameParticipants));

Answer №2

There are various methods to accomplish this task, and it's recommended to explore other solutions provided as well. Below is a revised version of your code with some minor corrections made in the if condition.

const playersList = [{
    winner: 'Sam',
    loser: 'Bruce',
    loser_points: 10
  },
  {
    winner: 'Sam',
    loser: 'Hakim',
    loser_points: 9
  },
  {
    winner: 'Sam',
    loser: 'Paul',
    loser_points: 9
  }
];

const getPlayers = function(data) {
  const playerArr = [];
  
  for (let i = 0; i < data.length; i++) {
    // check and add winner to the array
    if (!playerArr.includes(data[i].winner))
      playerArr.push(data[i].winner);

    // check and add loser to the array
    if (!playerArr.includes(data[i].loser))
      playerArr.push(data[i].loser);
  }
  
  return playerArr;
};

console.log(getPlayers(playersList));

Answer №3

Utilize the Set method to create a unique list of data.

const playerNames = [{ winner: 'Sam', loser: 'Bruce', loser_points: 10 },{ winner: 'Sam', loser: 'Hakim', loser_points: 9 }];
const players = Array.from(new Set(playerNames.flatMap((node) => [node.winner, node.loser])));
console.log(players);

Answer №4

I decided to revise my solution inspired by the technique used by Elaine Alt, as I found their approach quite compelling!

(however, with the implementation of reduce)

function extractPlayers(games) {
    return Object.keys(
        games.reduce((accumulator, game) => {
            return {
                ...accumulator,
                [game.winner]: 1,
                [game.loser]: 1,
            };
        }, {})
    );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can jQuery.jScrollPane be set to consistently display a vertical scroll bar?

Can jQuery.jScrollPane be configured to consistently display a vertical scroll bar? Is there a hidden setting or API function that can achieve this? Ideally, without needing to adjust the content pane's height or other properties. ...

Is there a way to determine in FireBug the specific JavaScript code being received from the server following an Ajax request?

Within my HTML code, I am transmitting a dollar amount to the server in order to convert its currency within the application. Is there a way for me to use FireBug to track and view the JavaScript that is being received from the server following this Ajax ...

accept various query parameters in a GET request in a REST API written in Node.js

Is there a way to dynamically receive multiple parameters in a GET request without knowing which ones will come and which ones won't, in order to filter using the find() method? This pertains to NODE JavaScript with Mongoose app.get('/venta&apos ...

Tips for utilizing numerous tables with multiple selection tags

I am struggling with a jQuery issue involving multiple container elements with the class "product-sizes". Each container contains a select option for choosing between inches and centimeters, which triggers the corresponding table display. The problem arise ...

Modifying the onclick function of an HTML select element - easy steps!

I have customized the click event on my select tag to trigger a specific action. However, when I click on the select tag, the default option list is also displayed. I want to bypass this default behavior and only execute my custom action when the select ta ...

Stopping the timer with clearInterval isn't functioning as expected

I posted my work online here: Instructions on how to reproduce: Click on a green pin on the map to select a station Fill in the fields for name and last name Sign on the canvas A timer should start counting down from 20 minutes If you click on the ...

Is it possible to add some color to the first table in the div

Is it possible to change the background color of the first table within this Div tag that contains three tables? <div id="WebPartWPQ2" width="100%" HasPers="false" allowExport="false"> <table width="100%" border="0" cellSpacing="0" cellPadding= ...

Utilizing jQuery to configure multiple selection options within OptGroup elements

I am working with a Multi-Select list that has OptGroups set up in the following way: <select multiple="multiple" id="idCountry"> <optgroup label="ASIA"> <option value="AUSTRALIA">AUSTRALIA</option> <option value ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

What is the best way to convert template interpolation using different words into a correct expression syntax in JavaScript regex?

I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms: foo{{bar}} {{foo}}bar foo{{bar}}baz {{foo}}{{bar}} foo {{foo}} {{foo}}bar{{baz}} The text interpo ...

I encountered an error stating "angular not found" when attempting to dynamically load my Angular scripts

My Angular application is running smoothly. However, I found it tedious to include multiple script tags in my HTML documents every time. To simplify this process, I decided to create a small script that would automatically generate the necessary tags for m ...

Using jQuery to send a post request to a PHP script using either JavaScript or PHP

Just a quick question for those with experience. I am working on a page where I have implemented a jQuery AJAX post to another PHP page that contains JavaScript. My concern is, will the JavaScript code also be executed? Another scenario to consider is if ...

Vue continues to execute the timeout method even after it has been successfully cleared

In an attempt to postpone an API call for fetching search results, I have implemented the use of setTimeout and clearTimeout methods in my Vue application. A watcher has been set up on a search variable so that whenever it changes, the corresponding code ...

jQuery: extracting unique content from DOM elements using filter/get/select techniques

After retrieving an XML document using AJAX, I'm faced with the challenge of filtering out duplicate <category> elements based on their unique HTML content. In the XML data, there are four <category> elements: 2 x DVR, 1 x Alarms, 1 x Bull ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

Utilizing the Tooltip Directive when hovering over the designated tooltip region

One of my requirements is that when a user hovers over an icon, a tooltip should appear allowing the user to click on a URL within the tooltip. Additionally, I need the tooltip element inside the icon div to be appended to the body when hovered over and re ...

Is it possible to utilize Sequelize model methods to articulate the given SQL query effectively?

I've been spending hours trying to convert the following SQL query into a Sequelize model method like findOne() - SELECT * FROM "Tariffs" WHERE "tariffType" = 'DateRange' AND (('${body.startDate}' BETWEEN "startDate" AND "endDate" ...

The jQuery ajax function is failing to return any results

Here is the code snippet I am working with: $("#MainContent_btnSave").click(function () { if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) { alert("Please make sure to fill in all required ...

Trigger a click event upon page load using jQuery or JavaScript

I tried searching for this functionality on a different website, but it didn't work on my site. Can you help me figure out how to trigger a click event on page load? On one of my pages, a popup box appears when I click on a "project" link. Here is th ...