0

I want to delete one of the duplicated elements in a more dimensional array. This was my code so far:

for (var i = 0; i< blog.length; i++){
  for (var i = 0; i< blog.length; i++){
     var check1 = blog[i][1];
     var check2 = blog[j][1];
     //check1 = 120;;200  check2 = 130;;180
     if (check1 == check2){
        blog[i].splice(i, 1);
     }
  }
}
  • I want only delete the first element of the duplicated pair.
  • Can you give me a more smart code for that?
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
zyrup
  • 691
  • 2
  • 10
  • 18

1 Answers1

0

Loop downwards over the array and store found values as keys in an Object so you can do a quick in check.

var blog = [['a', 0], ['b', 1], ['c', 2], ['d', 3], ['e', 0]]; // test var

var i = blog.length, // var to loop over
    o = {}, // obj to hold keys
    b2 = []; // temporary array
while (i--) { // looping down
    if (false === blog[i][1] in o) { // if not already seen
        o[blog[i][1]] = 1; // mark as seen
        b2[b2.length] = blog[i]; // add to temporary array
    }
}
blog = b2.reverse(); // temporary array is backwards so reverse it and set `blog`
// [["b", 1], ["c", 2], ["d", 3], ["e", 0]]
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 1
    This could also be an opportunity to use the **amazing** "[goes to operator](http://blogs.msdn.com/b/ericlippert/archive/2010/04/01/somelastminutefeatures.aspx)", `while (i --> 0) { /* .. */ }`, [but I'll not put that in my answer now](http://stackoverflow.com/q/1642028/1615483). – Paul S. Mar 02 '13 at 14:48
  • That worked fine for me: var i = (blog.length-1), o = {}, f2 = []; while(i >= 0){ if(false === blog[i][1] in o){ o[blog[i][1]] = 1; f2.push(blog[i]); } i--; } blog = f2; Thank you! – zyrup Mar 02 '13 at 16:13