Provide me with the list of names from the array of objects

I'm struggling to find a way to print the array of values in a specific order after looping through an object.

**Here is the challenge:**

Given a set of game outcome records, the task is to identify all the players and create an array of their names in the order they appear.

Example Input:

[
  { winner: 'Alishah', loser: 'Bob', loser_points: 3 },
  { winner: 'Maria', loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise', loser: 'Bob', loser_points: 2 },
  { winner: 'Elise', loser: 'Maria', loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria', loser_points: 2 },
  { winner: 'Maria', loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin', loser: 'Elise', loser_points: 2 }
]

Expected Result:

['Alishah', 'Bob', 'Maria', 'Xu Jin', 'Elise']

**Here's the code snippet I've been working on:**

let data = [
  { winner: 'Alishah', loser: 'Bob', loser_points: 3 },
  { winner: 'Maria', loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise', loser: 'Bob', loser_points: 2 },
  { winner: 'Elise', loser: 'Maria', loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria', loser_points: 2 },
  { winner: 'Maria', loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin', loser: 'Elise', loser_points: 2 }
];

   
console.log(main(data));

Answer №1

To accomplish this task, you can utilize the .flatMap() method along with the Set() constructor:

let data = [
  { winner: 'Alishah', loser: 'Bob',    loser_points: 3 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise',   loser: 'Bob',    loser_points: 2 },
  { winner: 'Elise',   loser: 'Maria',  loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria',  loser_points: 2 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin',  loser: 'Elise',  loser_points: 2 }
];

const res = [...new Set(data.flatMap(x=>[x.winner, x.loser]))]
console.log( res )

Explanation:

  • By applying the .flatMap() method, we obtain an array of arrays, where each inner array contains the names of the winning and losing players.
  • Subsequently, we flatten the array to consolidate all player names into a single array.
  • Lastly, by using [...new Set(array)], we are able to retrieve a unique list of player names to meet the intended outcome.

Answer №2

If you want to extract unique names from an array using JavaScript, you can utilize Array.reduce() together with Set.

By leveraging Array.reduce(), you can loop through the array and collect all names into a new array.

Afterwards, you can transform this array into a Set to automatically eliminate duplicates. To convert the set back to an array, simply use the spread syntax: [...new Set(array)]

const data = [
  { name: 'Alice',   age: 25 },
  { name: 'Bob',     age: 30 },
  { name: 'Alice',   age: 27 },
  { name: 'Kim',     age: 22 },
  { name: 'Bob',     age: 28 }
]

const uniqueNames = [...new Set(data.reduce((acc, cur) => [...acc, cur.name], []))]

console.log(uniqueNames)

Answer №3

const getUniquePlayers = collection.reduce((acc, player) => {
    if(!acc.inStore[player.winner]) {
        acc.players.push(player.winner)
        acc.inStore[player.winner] = true
    }
    if(!acc.inStore[player.loser]) {
        acc.players.push(player.loser)
        acc.inStore[player.loser] = true
    }
    return acc;
}, {players: [], inStore: {}}).players

// Result: ["Alishah", "Bob", "Maria", "Xu Jin", "Elise"]

Answer №4

Utilize the reduce method along with includes

console.clear();

"use strict";

const scores = [
  { winner: 'Alishah', loser: 'Bob',    loser_points: 3 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise',   loser: 'Bob',    loser_points: 2 },
  { winner: 'Elise',   loser: 'Maria',  loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria',  loser_points: 2 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin',  loser: 'Elise',  loser_points: 2 }
]

function filterPlayers(coll, {winner, loser}) {
  if (!coll.includes(winner)) {
    coll.push(winner)
  }
  if (!coll.includes(loser)) {
    coll.push(loser)
  }
  return coll;
}

var playersList = scores.reduce(filterPlayers, [])
console.log(playersList)

Answer №5

After analyzing your code and the expected outcome, it appears that you may have forgotten to include the 'looser' name in the 'arr' array. One way to resolve this issue is by utilizing the 'reduce' method available in JavaScript arrays:

const arr = outcomes.reduce((completeList,{winner, looser}) => {
    const extraNames = [winner, looser]
        .filter(x => !completeList.includes(x));
    return [
        ...completeList,
        ...extraNames
    ];
}, []);

Answer №6

Utilizing map and filter methods

let participants = [
  { winner: 'Alishah', loser: 'Bob',    loser_points: 3 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise',   loser: 'Bob',    loser_points: 2 },
  { winner: 'Elise',   loser: 'Maria',  loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria',  loser_points: 2 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin',  loser: 'Elise',  loser_points: 2 }
];

let uniqueWinners = participants.map(item => item.winner).filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueWinners);

Answer №7

const tournamentResults = [
  { winner: 'Alishah', loser: 'Bob',    loser_points: 3 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 1 },
  { winner: 'Elise',   loser: 'Bob',    loser_points: 2 },
  { winner: 'Elise',   loser: 'Maria',  loser_points: 4 },
  { winner: 'Alishah', loser: 'Maria',  loser_points: 2 },
  { winner: 'Maria',   loser: 'Xu Jin', loser_points: 3 },
  { winner: 'Xu Jin',  loser: 'Elise',  loser_points: 2 }
];

const players = tournamentResults.reduce((acc, cur) => {
  if(!acc.includes(cur.winner))
  acc.push(cur.winner);
  if(!acc.includes(cur.loser))
  acc.push(cur.loser);
  return acc;
}, []).join(",");

console.log(players);

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

Adding JSON data to a table with the keys in the first row is a simple process that can be achieved

Previously, I have created tables with XML formatted results and JSON data in the "key: data" format. To access the data, I would use syntax like results.heading1 and then map the data into a table by matching the key with the data. Now, a new client is o ...

Listen for the modified value in a directive with AngularJS

I am currently working on implementing a directive that can draw a chart based on specified values. What I am aiming for is to pass the data necessary for the plot directly from the template rather than using ng-model, as my current solution requires. I ...

Techniques for transferring array values to a function in JavaScript

I am seeking guidance on how to pass values in an array to the ajax function in JavaScript. The goal is to call the function in JavaScript for each ID present in the array. I am looking for a way to pass each ID in the array and then call the function ac ...

The jQuery placeholder plugin encounters an error stating 'jQuery is not defined'

Having an issue on this specific page where I keep encountering a 'jQuery is not defined' error in both Chrome and IE because of the jQuery placeholder script. The declaration of jQuery comes before the plugin script. Checked for any conflicts ...

Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially r ...

most efficient method for verifying if three text fields have no content

Is there a way to verify that the sum of the values in three textboxes is greater than a blank value? <asp:TextBox ID="tbDate" runat="server"></asp:TextBox> <asp:TextBox ID="tbHour" runat="server"></asp:TextBox> <asp ...

I'm experiencing an out of memory issue and struggling to identify the root cause

Several tips from here were used long ago to create this code. var tm; var tn; var rot = true; var rot2 = true; var th = 482; var tmh = 0; var $paneTarget = $('#lyr1'); var slideshow = { delay: 5000, actions:[], run: function() { ...

I need to sort my tags by comma and use MUI Select to filter them

[ {id: 'AjRzfMxbfJMphK144DIAr', title: 'javascript', tags: 'code,programining', notes: "This book is a must to", createdAt: 1671459053853} {id: 'kvdo7HrLr2GeOUX9j4qLq', title: 'css', tags: &ap ...

When using jQuery Ajax, only pass the query string if it is defined and not empty

Using jquery and ajax to communicate with a CMS API, I am constructing a query string to fetch data: region = typeof region !== 'undefined' ? 'region='+region : ''; centre = typeof centre !== 'undefined' ? 'cen ...

Discovering and tallying a particular term within a text via JavaScript - a guide

In my current project, I have extracted an XML response and converted it into readable text. Here is a snippet of the converted XML: let XMLText = '<?xml version="1.0" encoding="utf-8"?> <BlockList> <CommittedB ...

Retrieving data with .getJSON and iterating over an array

I'm currently attempting to iterate through a multidimensional array, but I'm encountering difficulties. $.getJSON("file.json", function(json) { for(var i = 0; i < json.length; i++) { var county = json.data[i][9]; c ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Is it possible to match a String with the identifier of an array?

Hey there! I'm currently working on a project where I need to extract details for a specific item from one array by referencing another array. Here's the code snippet I have so far: foreach($json_items['result']['items'] as $ ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Guide to integrating Firebase token authentication with a web API2 controller

In order to pass a Firebase authentication token to a web API controller, I am following steps outlined in this StackOverflow post: stackoverflowpost The bearer token is included in the $http request headers. https://i.sstatic.net/GTJz0.png Despite addr ...

Validation in Laravel appears to be ineffective when managing schedules

I have a table that contains schedules for each subject. I want to ensure that every schedule is unique and not duplicated. The table includes columns for room, teacher, time, day, and checker who verifies the schedule. It's essential that there are n ...

Locate the nearest index within the array

I'm currently working with an array of "events" where the key assigned to each event corresponds to the Unix Timestamp of that particular event. To illustrate, consider the following array of event objects in JS: var MyEventsArray=[]; MyEventsArray[1 ...

One array comprises of all elements found in a separate array

After grappling with this problem for a while, I still haven't been able to find a solution. If I have 2 arrays structured like this: array1 = [ { name: 'John', age : 25}, { name: 'Jane', age : 58} ] array2 = [ { name: ...

Exploring the dynamic loading of JavaScript functions with Ajax in Dojo while passing arguments

Currently, I am working on implementing a require/load function that handles the retrieval and execution of remote JavaScript code. The function is functioning well, but I have been using a workaround to pass arguments by setting global variables. However, ...