0

This question comes up a lot, but my specific situation appears not to be covered by any SO answers I've reviewed.

I have a multidimensional array with some duplicate arrays which I'd like to remove.

[
    [8, 12],
    [8, 17],
    [8, 92],
    [8, 12]
]

[8, 12] appears twice. How can I remove this duplicate?

3
  • 2
    Did you try something ? Do you have performance constraints and a very big arrays ? Commented Sep 16, 2013 at 16:47
  • 2
    You can loop through them, create a new array, and check each element if its present in the new array before adding it. Commented Sep 16, 2013 at 16:50
  • 3
    What other SO posts did you view? All of them should work, only you need to change the comparison so that it considers the similar (but not identical) arrays equal. Commented Sep 16, 2013 at 16:54

1 Answer 1

2

What about the following:

var array1 = [[8,12],[8,17],[8,92],[8,12]];
var array2 = new Array();

for (var i=0; i<array1.length; i++) {
 var e1 = array1[i];
 var exists = false;
 for (var j=0; j<array2.length; j++) {
  if (array2[j][0] == e1[0] && array2[j][1] == e1[1]) exists = true;
 }
 if (exists == false) {
  array2[array2.length] = e1;
 }
}

the array2 is now array1 without duplicates. this should be way too slow for realtime game programming, but it should work. I am sorry, if I coded something wrong, it isn't intentional. I didn't test the code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.