Consider an array of 30K (or more) sub-arrays, something like this:
[[A,B],[C,D],[E,F],[G,H]......[D,C],[H,G]]
What is the fastest way to remove all mirrored sub-arrays from the main array ? As in: in the above example, say, remove [D,C]
OR [C,D]
but NOT both?
What I have tried:
.splice()
with a backwards for
loop. forEach
loop. .stringify()
and .join()
. if (array.indexOf([array[i][1], array[i][0]) > -1)
if (array.indexOf(array[i].reverse()) > -1)
Nothing seems to be working and in forEach
loop case combined with string comparison freezes the browser.
A simple code to first see if it works at all:
for (var i=0; i < l; i++) {
if (arr.indexOf([arr[i][1],arr[i][0]]) > -1) console.log(arr[i])
}
most other things that I tried are variations of the above code but every time the entire array gets logged to the console.
UPDATE: sub-arrays are basically just English words, more specifically synonym pairs. so ["always","forever"]
exists and so does [forever, always]
. this isn't the case for every pair/word but there are many such cases throughout the array. I want to loop through the entire array and remove any 1 array of such "pairs". which one is removed doesn't matter. in the end, the resulting array should have no "mirror" arrays. I hope this better clarifies what I am trying to achieve.
Using indexOf
with an array literal as argument is always going to return -1. That array literal is a new array, and so that reference will not be present in your array. Objects (arrays) are equal when they reference the same memory location.
As a solution you could sort each pair, and then map that pair to JSON. This array of JSON strings can then be fed to a Map
, so that the JSON will serve as unique key. The corresponding value can be the original pair.
This solution will retain the last occurrence of mirrors/duplicates:
let arr = [["a", "b"], ["f", "c"], ["m", "q"], ["b", "a"], ["q", "s"], ["c", "f"], ["b", "z"]]; let map = new Map(arr.map(pair => [JSON.stringify([...pair].sort()), pair])); let result = [...map.values()]; console.log(result);
If you don't mind that the original array is mutated, then you can replace [...pair]
with just pair
. The result will then also have its pairs sorted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.