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

Exepected Output: [ [1,2],[5,8] ]

Dear all, is there a way to filter an array of coordinates from an array of coordinates? There are codes similar to this from element of array at here, but I am unsure on filtering 2d-nested array.

I will appreciate if anyone can guide me 🙂

3

Answers


  1. Try this one.

    let big_coordinates_arr  =[ [1,2],[3,4],[5,8],[7,9]] ;
    let small_coordinates_arr=[ [3,4],[7,9] ] ;
    
    function check(data) {
        for (i = 0; i < small_coordinates_arr.length; i++) {
            //checking both 0 and 1 index at the same time and
            //eliminating them immediately.
            if (data[0] === small_coordinates_arr[i][0] && data[1] === small_coordinates_arr[i][1]) {
                return false;
            }
        }
        //if element doesn't match keep them by returning true
        return true;
    }
    
    console.log(big_coordinates_arr.filter(check)); //you will get [ [1,2],[5,8] ]
    

    But this solution works if you want to exclude all matched elements. I mean, if big_coordinates_arr has [3,4] element twice or more, this algorithm eliminates all of them.

    Login or Signup to reply.
  2. Another solution using Array.filter() and Array.every() to do it

    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)
    Login or Signup to reply.
  3. You can convert the coordinates into string for easier comparison. Then just filter the strings our from the big_cordinates. 🙂

    sm_coordinates = small_coordinates_arr.map(e => e.toString())
    filtered_bif = big_coordinates_arr.filter(e => !sm_coordinates.includes(e.toString()))
    
    
    let small_coordinates_arr=[ [3,4],[7,9] ] ;
    let big_coordinates_arr  =[ [1,2],[3,4],[5,8],[7,9]] ;
    
    
    const small_coordinates = small_coordinates_arr.map(e => e.toString());
    const filtered_coordinates = big_coordinates_arr.filter(e => !small_coordinates.includes(e.toString()));
    
    console.log(filtered_coordinates);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search