skip to Main Content
let big_coordinates_arr  =[ [1,2],[3,4],[5,8],[7,9]] ;
let small_coordinates_arr=[ [3,4],[7,9] ] ;

let is_same = (arr1,arr2) => arr1.length == arr2.length && arr1.every(function(element, index) {
    return element === arr2[index]; 
});

let result = big_coordinates_arr.filter(c1 => !small_coordinates_arr.some(c2 => is_same(c1,c2)))
console.log(result)
let big_coordinates_arr  =[ [[1,2],[3,4]], [[3,4],[1,2]] , [[5,8],[7,9]] , [[7,1],[6,5]] , [3,6],[7,3] ] ;
let small_coordinates_arr=[ [[3,4],[1,2]] , [[7,1],[6,5]] ] ;
Expected output should be [  [[5,8],[7,9]] , [3,6],[7,3] ]

The code snippet shows the filter output of the coordinates array from another coordinates array.

My question is about filtering a segment array from another segment array. In my example, I have this [[1,2],[3,4]] which represents a segment (2 points), which means that [[1,2],[3,4]] and [[3,4],[1,2]] can be assumed to be the same because you can interchange the 2 points and still form the same segment.

May I ask how to produce the expected output?

I will really appreciate any help I can get:)

2

Answers


  1. By sorting the arrays and all their nested arrays, you’ll be able to achieve the expected output,

    let bigArr = [[[1, 2], [3, 4]], [[3, 4], [1, 2]], [[5, 8], [7, 9]], [[7, 1], [6, 5]], [3, 6], [7, 3]];
    let smallArr = [[[3, 4], [1, 2]], [[7, 1], [6, 5]]];
    
    function isSame(a, b) {
      for (let i = 0; i < a.length; i++) {
        if (Array.isArray(a[i]) && Array.isArray(b[i])) {
          if (!isSame(a[i], b[i])) return false;
        } else if (a[i] !== b[i]) {
          return false;
        }
      }
      return true;
    }
    
    function sameElems(arr1, arr2) {
      let sortedArr1 = arr1.map(x => (Array.isArray(x) ? x.slice().sort() : x)).sort();
      let sortedArr2 = arr2.map(x => (Array.isArray(x) ? x.slice().sort() : x)).sort();
      return isSame(sortedArr1, sortedArr2);
    }
    
    let result = bigArr.filter(bigCoords => {
      return !smallArr.some(smallCoords => sameElems(bigCoords, smallCoords));
    });
    
    console.log(result);
    Login or Signup to reply.
  2. I have done multiple tests and then after I get the below response.

    function isSame(seg1, seg2) {
      return (
        (seg1[0][0] === seg2[0][0] && seg1[0][1] === seg2[0][1] && seg1[1][0] === seg2[1][0] && seg1[1][1] === seg2[1][1]) ||
        (seg1[0][0] === seg2[1][0] && seg1[0][1] === seg2[1][1] && seg1[1][0] === seg2[0][0] && seg1[1][1] === seg2[0][1])
      );
    }
    
    let big_coordinates_arr = [[[1,2],[3,4]], [[3,4],[1,2]] , [[5,8],[7,9]] , [[7,1],[6,5]] , [3,6],[7,3]];
    let small_coordinates_arr = [[[3,4],[1,2]] , [[7,1],[6,5]]];
    
    let result = big_coordinates_arr.filter(seg1 => !small_coordinates_arr.some(seg2 => isSame(seg1, seg2)));
    
    console.log(result);

    Hope you will get an answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search