What is the best method for eliminating two symmetric arrays from a larger array using JavaScript?

Here is an example array I have:

[["", "A"], ["B", ""], ["A", ""], ["", "A"]]

I am looking to remove the first and third arrays as they are symmetrical, resulting in this array:

[["B", ""], ["", "A"]]

If anyone knows how to achieve this, please share. I can utilize any data structure and algorithms without concern for time and space complexity.

Answer №1

One potential resolution,

See it in action:

const info = [["", "A"], ["B", ""], ["A", ""], ["", "A"]]
const facts = [["", "A"], ["B", ""], ["A", ""], ["", "A"], ["", "B"]]

const areOpposite = (x, y) => JSON.stringify(x) === JSON.stringify(y.reverse()); 

const getMirrorIndices = (data) => data.reduce((acc, x, indexX) => {
  data.forEach((y, indexY) => (areOpposite(x, y)) && acc.push([indexX, indexY]));   
  return acc;
}, []);

const duoToErase = (data) => data.at(0).sort((x, y) => y - x);

const eraseOpposites = (data) => {
  const collection = [...data];
  let indices = getMirrorIndices(collection);
  
  while(indices.length > 0) {
    duoToErase(indices).forEach(index => collection.splice(index, 1));
    indices = getMirrorIndices(collection);
  };
  
  return collection;
};

console.log(eraseOpposites(info));
console.log(eraseOpposites(facts));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Answer №2

After experimenting with it today, I came up with my own solution:

let elements = [["", "A"], ["B", ""], ["A", ""], ["", "A"],["", "B"],["","C"],["C",""],["","B"]];

const removeSymmetricElements = (array) => {
  let result = [];

  for (let i = 0; i < array.length; i++) {
    if (!isSymmetricElementIncluded(result, array[i])) {
      result = [...result, array[i]];
    } else {
      result = result.filter(
        (item) => item[0] !== array[i][1] || item[1] !== array[i][0]
      );
    }
  }
  return result;

  function isSymmetricElementIncluded(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i][0] === b[1] && a[i][1] === b[0]) {
        return true;
      }
    }
    return false;
  }
};

console.log(removeSymmetricElements(elements))

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

Tips for updating a single attribute in Mongoose

I am currently using mongoose version 4.1.8 and below is an example of my mongo db schema: (function() { 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const DataCodeSchema = new Schema({ ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

What impact does async await have on the asynchronous nature of JavaScript?

Although JavaScript is synchronous, we utilize callback promises and async-await to achieve asynchronous behavior. However, with async-await, the code waits for the await statement to be completed before proceeding to the next statement, which may seem s ...

Is the order of query execution being altered when using the MongoClient in Node.js?

I am currently developing a registration API endpoint that utilizes MongoDB to validate two specific conditions: If the username provided already exists in the database, it will return a status of 500 If the email address provided already exists in the da ...

Adjusting the z-axis rotation in a three.js animated scene

Is there a way to add a function that changes the Z rotation value of the teapot from within the updateTeapot function? I came across this helpful answer on Three.js camera tilt up or down and keep horizon level. However, I am unsure how to integrate a z ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

Creating a service function (constructor) in JavaScript

When working with AngularJs and calling a service method: app.service('nameService', function() { this.Service = function (){console.log('hello')} } You can then use this service (object) like so: nameService.Service() My question is, ...

"Implementing filtering logic for an array of objects with multiple conditions in a React application

I am looking to apply filters to a person list based on criteria such as city, job, age, and gender. How can I apply filters based on five conditions in React? I tried using filter chaining but it did not work for me. In the useEffect hook, I applied indiv ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

What is the reason behind "Script" being considered the offspring of "Body"?

Unfortunately, I struggle with HTML/CSS/Javascript and am just trying to get through my exams. I have the code snippet below: <script> window.onload=function() { var c = document.body.childNodes; var txt = ""; var i; for ...

Transferring Composite Data Structures from JavaScript to a WCF RESTful Service

Below are the code snippets: 1. The intricate object: [DataContract] public class NewUser { [DataMember(Name = "Email")] public string Email { get; set; } [DataMember(Name = "FirstName")] public string FirstName { get; set; } [DataMem ...

What are the steps to implementing partial page functionality with the $http service in Angular?

Could someone assist me with executing an operation once a partial page has been successfully loaded using the $http service in Angular? The operation involves checking a checkbox based on the scope value. I have included the source code below: Here i ...

Tips for applying a jQuery class when the page is both scrolled and clicked

As I work on building a HTML website, I encountered an interesting challenge. I want to create a dynamic feature where, as users scroll through the page, certain sections are highlighted in the navigation menu based on their view. While I have managed to a ...

JavaScript post method is failing to work, while it successfully runs in POSTMAN

Attempting to send a message to Android devices through a POST request to Firebase Cloud Messaging. When using POSTMAN, the server responds with a success response 200. However, when attempting the same operation with JavaScript using an AJAX request, I r ...

Is it possible to change the transition behavior within a Vue component?

Is there a way to modify or replace transitions within a Vue component? I am currently using Buefy components for my website, but I have encountered an issue with certain components like collapse that have a slot with a fade transition that I do not pref ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

What is the best way to display a template after submitting data via AJAX in the Flask framework?

Encountering an issue where I am unable to open render_template after posting data with ajax. Below is my ajax code: if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'neg ...

Is there a way to programmatically display a Chakra-UI Toast?

I'm currently struggling to programmatically display a Chakra-UI Toast using the Chakra-UI React.js component library. The Chakra-UI Toast documentation only provides examples of showing the toast based on a button click, but I'm looking to show ...