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

Time:09-10

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.

CodePudding user response:

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 }

CodePudding user response:

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))

CodePudding user response:

maybe this is what you need.

const a = [["", "A"], ["B", ""], ["A", ""], ["", "A"]]

const isSymmetry = (a, b) => {
  if(a.length !== b.length) return false;

  for(const i in a){
    const ib = b.length - 1 - i;
    if(a[i] !== b[ib]) return false
  }

  return true;
}

const isSame = (a, b) => {
  return a.every((item, index) => item === b[index])
}

const removeSymmetryAndSame = (arr) => {
  const res = []
  for(let i =  0; i < arr.length; i  ){
    let isPass = true;
    for(let y = i 1; y <= arr.length-1; y  ){
      if((isSymmetry(arr[i], arr[y]) || isSame(arr[i], arr[y]))){
        isPass = false;
        arr.splice(y, 1)
      }
    }
    if(isPass){
      res.push(arr[i])
    }
  }
  return res;
}

const b = removeSymmetryAndSame(a)
console.log(b)
  • Related