let mirror_arr=[ [1,2],[3,2],[1,4],[8,1],[5,4],[2,1],[3,5],[1,8],[3,2],[2,3] ]
filtered_mirror=[ [1,2],[3,2],[1,4],[8,1],[5,4],[3,5] ];
This algorithm filter out all the mirror ones. For example, [1,2] is a mirror of [2,1], so it will be filtered by removing the mirrors. Are there any short method to do this in Javascript? Thank you for reading :) My codepen solution is here and I am almost solved it. It is just that I have to remove the duplicate ones.
I've assumed that you don't want duplicates either as you didn't have a second [3,2] in your expected output. From your codepen it looks like you're familiar with Set and JSON.stringify .
let mirror_arr = [ [1,2],[3,2],[1,4],[8,1],[5,4],[2,1],[3,5],[1,8],[3,2],[2,3] ];
let filtered = [];
let found_set = new Set();
for(let i = 0; i < mirror_arr.length; i++) {
let item = mirror_arr[i];
let string_item = JSON.stringify(item);
if(!found_set.has(string_item)) {
filtered.push(item);
found_set.add(string_item);
found_set.add( JSON.stringify([...item].reverse()) );
}
}
console.log(JSON.stringify(filtered));
.as-console-wrapper { max-height: 100% !important; top: 0; }