How to remove two symmetry arrays from an array in JavaScript?

Viewed 60

What I have is the array like this:

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

What I want is to remove the first and third array since they are symmetry, then the result look like this:

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

Can anybody tell me how to do it? I can use any data structure and algorithms and don't consider time and space complexity.

2 Answers

One of the possible solutions,

Live demo:

const data1 = [["", "A"], ["B", ""], ["A", ""], ["", "A"]]
const data2 = [["", "A"], ["B", ""], ["A", ""], ["", "A"], ["", "B"]]

const areSimmetric = (a, b) => JSON.stringify(a) === JSON.stringify(b.reverse()); 

const getSymmetricIndexes = (data) => data.reduce((acc, a, indexA) => {
  data.forEach((b, indexB) => (areSimmetric(a, b)) && acc.push([indexA, indexB]));   
  return acc;
}, []);

const pairToRemove = (data) => data.at(0).sort((a, b) => b - a);

const removeSimmetric = (data) => {
  const coll = [...data];
  let indexes = getSymmetricIndexes(coll);
  
  while(indexes.length > 0) {
    pairToRemove(indexes).forEach(index => coll.splice(index, 1));
    indexes = getSymmetricIndexes(coll);
  };
  
  return coll;
};

console.log(removeSimmetric(data1));
console.log(removeSimmetric(data2));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Today I tried it myself,this is my solution:

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

const removeSymmetryArray = (array) => {
  let res = [];

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

  function isSymmetryArrayIncludes(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(removeSymmetryArray(arr))
Related