How to organize items in an array based on paired values using Angular or Javascript?

In my current scenario, I am working with a substantial array containing 120 objects. Each object within the array possesses an id value and an opposite_id value, essentially forming pairs. I'm looking for the most efficient approach to iterate through each object and either store the pairs in a new array or present them together as a pair.

For instance:


    Obj1 = {
        id: 1,
        opposite_id: 2,
        descr: "This is the first object"
   },
   Obj2 = {
        id: 2,
        opposite_id: 1,
        descr: "This is the second object"
   },
    Obj3 = {
        id: 3,
        opposite_id: 6,
        descr: "This is the third object"
   }

I aim to showcase Obj1 and Obj2 concurrently (ideally utilizing ng-repeat) as a pair without displaying both Obj2 and Obj1 to avoid repetition. Figuring out how to achieve this specific task is proving challenging for me, any guidance on this matter would be highly appreciated! Thank you

Answer №1

Why don't we try pairing them this way?

var app = angular.module("app", []);

app.controller("controller", function($scope) {
  var users = [{
    "id": 11,
    "user": {
      "id": 5,
      "first_name": "",
      "last_name": ""
    },
    "opponent": 2
  }, {
    "id": 12,
    "user": {
      "id": 6,
      "first_name": "",
      "last_name": ""
    },
    "opponent": 3
  }, {
    "id": 13,
    "user": {
      "id": 2,
      "first_name": "",
      "last_name": ""
    },
    "opponent": 5
  }, {
    "id": 14,
    "user": {
      "id": 3,
      "first_name": "",
      "last_name": ""
    },
    "opponent": 6
  }];

  $scope.pairs = [];
  var alreadyPaired = []; // storing ids of paired users

  for (var i = 0; i < users.length; i++) {
    var user = users[i];
    
    // pair the users if they haven't been paired before
    if (alreadyPaired.indexOf(user.user.id) === -1) {
      var opponent = null;

      for (var j = 0; j < users.length; j++) {
        if (users[j].user.id === user.opponent) {
          opponent = users[j];
        }
      }

      $scope.pairs.push({
        user1: user,
        user2: opponent
      });

      alreadyPaired.push(user.user.id);
      alreadyPaired.push(opponent.user.id);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
  <h3>Pairs</h3>
  <table>
    <thead>
      <tr>
        <th>User</th>
        <th>Opponent</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="pair in pairs">
        <td>{{pair.user1.user.id}}</td>
        <td>{{pair.user2.user.id}}</td>
      </tr>
    </tbody>
  </table>
</div>

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

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

Eliminating a particular element from an Array

As an illustration, there exists an array of objects in the following format: var myarray = [{ id: 01, name: alison, active: false}, { id: 04, name: drex, active: true}, { id: 08, name: farel, active: true}, { ...

Using V-model in conjunction with the boostrap-vue b-table component

I am attempting to bind v-model by passing the value inside the items array. However, the binding is not functioning correctly. The main objective here is to utilize a store since all these values are utilized across multiple "wizard" components. Whe ...

Tips for simulating a DOM element in Jasmine so that it is accessible to the controller

Trying to simulate a DOM element in my jasmine test it('Testing radio button change', function () { simElement = angular.element("<div><input class='my_radio' type='radio' /></div>"); si ...

The jQuery UI Tab is failing to scroll within its container

Scenario : I am facing an issue with a scrollable container in IE8. The containing div is supposed to be scrollable and it holds my jquery UI tab div. Issue: While scrolling the container in IE8, other content within it also scrolls, but the jQuery UI t ...

What is the best way to retrieve a value from an array?

Using ASP.net Core, I receive information from my API. In Angular, the data looks like this: 0: {Id: 3, Role_Name: 'ITAdmin'} 1: {Id: 4, Role_Name: 'Admin'} 2: {Id: 5, Role_Name: 'user'} I want to extract values from this arr ...

Creating a Loop with JavaScript through a List

My current API response format is: "imagePath": "path1", Here is the JavaScript code I am using: <div className="flexAlignCenterJustifyCenter"> {event.imagePath ? ( <img src={event.imagePath} onErro ...

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Tips on managing and responding to external events in ngapp

Currently, I'm in the process of constructing an angular application within the SharePoint environment (although this query does not pertain to SharePoint). I've created a page that contains a div with an angular app directive (comprising a form ...

Combining multiple JSON files into a single JSON object with duplicate keys

I'm currently facing a challenge where I need to combine multiple JSON objects into one, but I am encountering difficulties when trying to merge objects with identical keys. Consider the following JSON structures: {K1 - V1} {K2 - V2} {K3 - V3} {K1 - ...

How can I use React.JS to scroll horizontally to a specific div id?

scrollCustom() { document.getElementById("myID").scrollIntoView({"block":"center"}) } My attempt at using scrollIntoView({"block":"center"}) was flawless in Chrome, but encountered problems in Internet Explorer! ...

Deactivate Date Field for Editing Orders in WooCommerce

Is there a way to deactivate the Date Created textbox on the Edit Orders page of Woocommerce? I attempted to use pointer-events: none; but unfortunately, it did not have any effect. I am seeking a method to disable the Date Created field. https://i.sstat ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

Contrasting characteristics of indexing and slicing within numpy structured arrays

Imagine you have a structured array a: import numpy as np a = np.array([1, 2, 3, 4, 5, 6], dtype=[('val', 'i4')]) print(a) [(1,) (2,) (3,) (4,) (5,) (6,)] Now, when it comes to changing one of the entries to a different value, there ...

Redux Persist causes the redux state to become undefined

I recently added redux-persist to my project and now I am facing an issue where all of my Redux states are returning undefined. Previously, all the Redux states were functioning properly. However, after incorporating redux-persist, they are no longer work ...

Access a different tab through the utilization of JavaScript functions

Hi everyone, I recently created tabs using bootstrap, but I am facing a challenge with a specific scenario. I need the active tab to switch to another tab when a submit button is clicked. <div id="checkout-progress"> <ul class="nav nav-tabs"& ...

The initialization process removes the 'const' qualifier from the target type of the pointer

Hey there! I'm struggling with sorting an array of structs containing char names alphabetically using qsort. However, I keep encountering an error message that says "initialization discards ‘const’ qualifier from pointer target type". I'm pre ...

What is the best way to update a CSS href using window.open with JavaScript?

I am trying to dynamically change the CSS href by using window.open in JavaScript. <a class="cssButton" id="Launch" target="_blank" data-baseref="Example/index.html?" href="Example/index.html?" >Launch Example</a> I want to transform it into: ...

Exploring the world of accessing JSON data

My attempt to work with the Steam API is encountering some obstacles. The beginning of the JSON file is structured like this: { "playerstats": { "steamID": "XXXXXXXXXXXX", "gameName": "ValveTestApp260", "stats": [ { "name" ...