How to get distinct values from an array of arrays in JavaScript using the filter() method?Get all unique values in a JavaScript array (remove duplicates)How do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?Set a default parameter value for a JavaScript functionSort array of objects by string property valueHow to check whether a string contains a substring in JavaScript?Get all unique values in a JavaScript array (remove duplicates)How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Should my "average" PC be able to discern the potential of encountering a gelatinous cube from subtle clues?

"Silverware", "Tableware", and "Dishes"

How could Tony Stark wield the Infinity Nano Gauntlet - at all?

What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?

Can I submit a paper under an alias so as to avoid trouble in my country?

How big would a Daddy Longlegs Spider need to be to kill an average Human?

Use of vor in this sentence

Was Switzerland really impossible to invade during WW2?

Sleeping solo in a double sleeping bag

I think my coworker went through my notebook and took my project ideas

Designing a prison for a telekinetic race

My two team members in a remote location don't get along with each other; how can I improve working relations?

Church Booleans

Did the twin engined Lazair ultralight have a throttle for each engine?

Are required indicators necessary for radio buttons?

Is there any road between the CA State Route 120 and Sherman Pass Road (Forest Route 22S0) that crosses Yosemite/Serria/Sequoia National Park/Forest?

What professions does medieval village with a population of 100 need?

How to compare two different formulations of a problem?

How to avoid using System.String with Rfc2898DeriveBytes in C#

Mixing colours for a symbol

How do you call it when two celestial bodies come as close to each other as they will in their current orbits?

Why would the President need briefings on UFOs?

Are there reliable, formulaic ways to form chords on the guitar?

Sous vide chicken without an internal temperature of 165



How to get distinct values from an array of arrays in JavaScript using the filter() method?


Get all unique values in a JavaScript array (remove duplicates)How do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?Set a default parameter value for a JavaScript functionSort array of objects by string property valueHow to check whether a string contains a substring in JavaScript?Get all unique values in a JavaScript array (remove duplicates)How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















I have an array like this:



let x = [[1, 2], [3, 4], [1, 2], [2, 1]];


What should I do to retrieve an array without the duplicates?



[[1, 2], [3, 4], [2, 1]];


I would like to use the filter method. I tried this but it doesn't work:



x.filter((value,index,self) => (self.indexOf(value) === index))









share|improve this question


























  • stackoverflow.com/questions/1960473/…

    – Peter
    9 hours ago











  • Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

    – Seph Reed
    9 hours ago











  • Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

    – Seph Reed
    9 hours ago











  • @SephReed How about a Set combined with a hashing function?

    – Alireza
    9 hours ago






  • 1





    @Iwrestledabearonce.no. Fixed question

    – Snorlite
    9 hours ago

















7















I have an array like this:



let x = [[1, 2], [3, 4], [1, 2], [2, 1]];


What should I do to retrieve an array without the duplicates?



[[1, 2], [3, 4], [2, 1]];


I would like to use the filter method. I tried this but it doesn't work:



x.filter((value,index,self) => (self.indexOf(value) === index))









share|improve this question


























  • stackoverflow.com/questions/1960473/…

    – Peter
    9 hours ago











  • Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

    – Seph Reed
    9 hours ago











  • Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

    – Seph Reed
    9 hours ago











  • @SephReed How about a Set combined with a hashing function?

    – Alireza
    9 hours ago






  • 1





    @Iwrestledabearonce.no. Fixed question

    – Snorlite
    9 hours ago













7












7








7








I have an array like this:



let x = [[1, 2], [3, 4], [1, 2], [2, 1]];


What should I do to retrieve an array without the duplicates?



[[1, 2], [3, 4], [2, 1]];


I would like to use the filter method. I tried this but it doesn't work:



x.filter((value,index,self) => (self.indexOf(value) === index))









share|improve this question
















I have an array like this:



let x = [[1, 2], [3, 4], [1, 2], [2, 1]];


What should I do to retrieve an array without the duplicates?



[[1, 2], [3, 4], [2, 1]];


I would like to use the filter method. I tried this but it doesn't work:



x.filter((value,index,self) => (self.indexOf(value) === index))






javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 9 hours ago







Snorlite

















asked 9 hours ago









SnorliteSnorlite

438 bronze badges




438 bronze badges















  • stackoverflow.com/questions/1960473/…

    – Peter
    9 hours ago











  • Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

    – Seph Reed
    9 hours ago











  • Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

    – Seph Reed
    9 hours ago











  • @SephReed How about a Set combined with a hashing function?

    – Alireza
    9 hours ago






  • 1





    @Iwrestledabearonce.no. Fixed question

    – Snorlite
    9 hours ago

















  • stackoverflow.com/questions/1960473/…

    – Peter
    9 hours ago











  • Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

    – Seph Reed
    9 hours ago











  • Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

    – Seph Reed
    9 hours ago











  • @SephReed How about a Set combined with a hashing function?

    – Alireza
    9 hours ago






  • 1





    @Iwrestledabearonce.no. Fixed question

    – Snorlite
    9 hours ago
















stackoverflow.com/questions/1960473/…

– Peter
9 hours ago





stackoverflow.com/questions/1960473/…

– Peter
9 hours ago













Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

– Seph Reed
9 hours ago





Oof. This is a hard one. I can think of a few different ways to force it, but nothing eloquent. First heavy handed idea, is to not use filter and instead use a for loop.

– Seph Reed
9 hours ago













Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

– Seph Reed
9 hours ago





Hey guys, please read this users question before calling it a duplicate. They tried the things you've linked to. Ultimately, this question is a bit difficult to write the code for in an eloquent way.

– Seph Reed
9 hours ago













@SephReed How about a Set combined with a hashing function?

– Alireza
9 hours ago





@SephReed How about a Set combined with a hashing function?

– Alireza
9 hours ago




1




1





@Iwrestledabearonce.no. Fixed question

– Snorlite
9 hours ago





@Iwrestledabearonce.no. Fixed question

– Snorlite
9 hours ago












7 Answers
7






active

oldest

votes


















8














Try converting the inner arrays to a string, then filter the dupes and parse the string again.






let x = [[1, 2], [3, 4], [1, 2]];

var unique = x.map(ar=>JSON.stringify(ar))
.filter((itm, idx, arr) => arr.indexOf(itm) === idx)
.map(str=>JSON.parse(str));

console.log(unique);








share|improve this answer

























  • Thanks man, perfect.

    – Snorlite
    9 hours ago











  • Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

    – Bergi
    42 mins ago



















2














Okay, the string hash idea is brilliant. Props to I wrestled a bear once. I think the code itself could be a bit better though, so here's how I tend to do this type of thing:






let x = [[1, 2], [3, 4], [1, 2]];
const map = new Map();
x.forEach((item) => map.set(item.join(), item));
console.log(Array.from(map.values()));





And if you want an ugly one liner:






let x = [[1, 2], [3, 4], [1, 2]];
const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
console.log(noRepeats);








share|improve this answer
































    2














    This is a solution with time complexity of O(n) where n is the number of elements in your array.



    Using the filter method as the OP wants it:






     const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
    const s = new Set();


    const res = x.filter(el =>
    if(!s.has(el.join("")))
    s.add(el.join(""));
    return true;

    return false
    )

    console.log(res)





    My personal preference here is to use ForEach as it looks more readable.






    const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
    const s = new Set();
    const res = [];

    x.forEach(el =>
    if(!s.has(el.join("")))
    s.add(el.join(""));
    res.push(el)

    )

    console.log(res);





    We are using a Set and a simple combination of the elements of the array to make sure they are unique. Otherwise this would become O(n^2).






    share|improve this answer






















    • 1





      @DominikMatis Added a solution with filter.

      – Alireza
      9 hours ago











    • what is the inner array is more than two elements?

      – I wrestled a bear once.
      9 hours ago











    • if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

      – Alireza
      9 hours ago






    • 1





      it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

      – I wrestled a bear once.
      9 hours ago












    • NOICE! Thanks bearman :D

      – Alireza
      9 hours ago


















    1














    The equivalent to



    x.filter((value,index,self) => (self.indexOf(value) === index))


    would be



    x.filter((v,i,self) => 
    for1:
    for (let j = 0; j < self.length; j++)
    if (i == j)
    return true;

    if (self[j].length != v.length)
    continue;

    for (let k = 0; k < v.length; k++)
    if (self[j][k] != v[k])
    continue for1;


    return false;

    return true;
    )


    Unlike some of the other answers, this does not require a conversion to string and can thus work with more complex values.
    Use === instead of == if you want.



    The time complexity is not great, of course.






    share|improve this answer

























    • solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

      – I wrestled a bear once.
      8 hours ago












    • So you are saying it is not equivalent, because your version actually works?

      – Bergi
      39 mins ago











    • @Iwrestledabearonce. self is totally fine as a local variable name.

      – Bergi
      39 mins ago











    • Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

      – Bergi
      37 mins ago


















    1














    Effective solution:



    O(n) operations, where n is the length of x array



    O(n) memory space, where n is the length of x array






    const x = [[1, 2], [3, 4], [1, 2]];

    const arrayTable = Object.create(null);

    const uniqueArrays = x.filter(arr =>
    const arrStr = JSON.stringify(arr);

    if (!arrayTable[arrStr])
    arrayTable[arrStr] = true;
    return true;


    return false;
    );

    console.log(uniqueArrays);








    share|improve this answer








    New contributor



    akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




























      1














      Filter just causes things to get into O(n^2).



      The currently accepted answer uses .filter((itm, idx, arr) => arr.indexOf(itm) === idx) which will cause the array to be iterated each time during each iteration... n^2.



      Why even go there? Not only that, you need to parse in the end. It is a lot of excess.



      There is no real good way to filter without hitting O(n^2) here.



      Instead, just use reduce. It is very straightforward and fast easily accomplishing O(n).



      "Bin reduce the set to unique values."






      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
      console.log(y);





      If you were to have to go the route of filter, then n^2 must be used. You can iterate each item looking for existence using every.



      "Keep every element which does not have a previous duplicate."






      let x = [
      [1, 2],
      [3, 4],
      [1, 2],
      [2, 1]
      ];
      let y = x.filter((lx, li) =>
      x.every((rx, ri) =>
      rx == lx ||
      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
      );
      console.log(y);








      share|improve this answer

























      • Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

        – Snorlite
        5 hours ago


















      0














      indexOf does not work on identical instances of arrays/objects type elements within an array, as such arrays just hold references.



      In filter function instance you get via parameter v (in below code) is not the same instance as stored in array, making indexOf unable to return the index of it.



      In below code, by converting objects to strings we can use indexOf to find duplicates.






      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

      console.log(x.
      map(function(v)
      return JSON.stringify(v)
      )
      .filter(function(v, i, o)
      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
      )
      .map(function(v)
      return JSON.parse(v)
      )
      );








      share|improve this answer



























      • indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

        – I wrestled a bear once.
        9 hours ago











      • not if its an array of arrays, you cant find index of an array within an array using indexOf

        – Akash Shrivastava
        9 hours ago











      • if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

        – I wrestled a bear once.
        9 hours ago











      • you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

        – Akash Shrivastava
        9 hours ago






      • 1





        i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

        – I wrestled a bear once.
        8 hours ago













      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57562611%2fhow-to-get-distinct-values-from-an-array-of-arrays-in-javascript-using-the-filte%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      7 Answers
      7






      active

      oldest

      votes








      7 Answers
      7






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      8














      Try converting the inner arrays to a string, then filter the dupes and parse the string again.






      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);








      share|improve this answer

























      • Thanks man, perfect.

        – Snorlite
        9 hours ago











      • Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

        – Bergi
        42 mins ago
















      8














      Try converting the inner arrays to a string, then filter the dupes and parse the string again.






      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);








      share|improve this answer

























      • Thanks man, perfect.

        – Snorlite
        9 hours ago











      • Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

        – Bergi
        42 mins ago














      8












      8








      8







      Try converting the inner arrays to a string, then filter the dupes and parse the string again.






      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);








      share|improve this answer













      Try converting the inner arrays to a string, then filter the dupes and parse the string again.






      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);








      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);





      let x = [[1, 2], [3, 4], [1, 2]];

      var unique = x.map(ar=>JSON.stringify(ar))
      .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
      .map(str=>JSON.parse(str));

      console.log(unique);






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 9 hours ago









      I wrestled a bear once.I wrestled a bear once.

      15.6k14 gold badges51 silver badges104 bronze badges




      15.6k14 gold badges51 silver badges104 bronze badges















      • Thanks man, perfect.

        – Snorlite
        9 hours ago











      • Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

        – Bergi
        42 mins ago


















      • Thanks man, perfect.

        – Snorlite
        9 hours ago











      • Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

        – Bergi
        42 mins ago

















      Thanks man, perfect.

      – Snorlite
      9 hours ago





      Thanks man, perfect.

      – Snorlite
      9 hours ago













      Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

      – Bergi
      42 mins ago






      Much simpler: Array.from(new Set(arr.map(x=>JSON.stringify(x))), x=>JSON.parse(x))

      – Bergi
      42 mins ago














      2














      Okay, the string hash idea is brilliant. Props to I wrestled a bear once. I think the code itself could be a bit better though, so here's how I tend to do this type of thing:






      let x = [[1, 2], [3, 4], [1, 2]];
      const map = new Map();
      x.forEach((item) => map.set(item.join(), item));
      console.log(Array.from(map.values()));





      And if you want an ugly one liner:






      let x = [[1, 2], [3, 4], [1, 2]];
      const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
      console.log(noRepeats);








      share|improve this answer





























        2














        Okay, the string hash idea is brilliant. Props to I wrestled a bear once. I think the code itself could be a bit better though, so here's how I tend to do this type of thing:






        let x = [[1, 2], [3, 4], [1, 2]];
        const map = new Map();
        x.forEach((item) => map.set(item.join(), item));
        console.log(Array.from(map.values()));





        And if you want an ugly one liner:






        let x = [[1, 2], [3, 4], [1, 2]];
        const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
        console.log(noRepeats);








        share|improve this answer



























          2












          2








          2







          Okay, the string hash idea is brilliant. Props to I wrestled a bear once. I think the code itself could be a bit better though, so here's how I tend to do this type of thing:






          let x = [[1, 2], [3, 4], [1, 2]];
          const map = new Map();
          x.forEach((item) => map.set(item.join(), item));
          console.log(Array.from(map.values()));





          And if you want an ugly one liner:






          let x = [[1, 2], [3, 4], [1, 2]];
          const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
          console.log(noRepeats);








          share|improve this answer













          Okay, the string hash idea is brilliant. Props to I wrestled a bear once. I think the code itself could be a bit better though, so here's how I tend to do this type of thing:






          let x = [[1, 2], [3, 4], [1, 2]];
          const map = new Map();
          x.forEach((item) => map.set(item.join(), item));
          console.log(Array.from(map.values()));





          And if you want an ugly one liner:






          let x = [[1, 2], [3, 4], [1, 2]];
          const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
          console.log(noRepeats);








          let x = [[1, 2], [3, 4], [1, 2]];
          const map = new Map();
          x.forEach((item) => map.set(item.join(), item));
          console.log(Array.from(map.values()));





          let x = [[1, 2], [3, 4], [1, 2]];
          const map = new Map();
          x.forEach((item) => map.set(item.join(), item));
          console.log(Array.from(map.values()));





          let x = [[1, 2], [3, 4], [1, 2]];
          const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
          console.log(noRepeats);





          let x = [[1, 2], [3, 4], [1, 2]];
          const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
          console.log(noRepeats);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 9 hours ago









          Seph ReedSeph Reed

          1,41514 silver badges39 bronze badges




          1,41514 silver badges39 bronze badges
























              2














              This is a solution with time complexity of O(n) where n is the number of elements in your array.



              Using the filter method as the OP wants it:






               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





              My personal preference here is to use ForEach as it looks more readable.






              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);





              We are using a Set and a simple combination of the elements of the array to make sure they are unique. Otherwise this would become O(n^2).






              share|improve this answer






















              • 1





                @DominikMatis Added a solution with filter.

                – Alireza
                9 hours ago











              • what is the inner array is more than two elements?

                – I wrestled a bear once.
                9 hours ago











              • if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

                – Alireza
                9 hours ago






              • 1





                it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

                – I wrestled a bear once.
                9 hours ago












              • NOICE! Thanks bearman :D

                – Alireza
                9 hours ago















              2














              This is a solution with time complexity of O(n) where n is the number of elements in your array.



              Using the filter method as the OP wants it:






               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





              My personal preference here is to use ForEach as it looks more readable.






              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);





              We are using a Set and a simple combination of the elements of the array to make sure they are unique. Otherwise this would become O(n^2).






              share|improve this answer






















              • 1





                @DominikMatis Added a solution with filter.

                – Alireza
                9 hours ago











              • what is the inner array is more than two elements?

                – I wrestled a bear once.
                9 hours ago











              • if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

                – Alireza
                9 hours ago






              • 1





                it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

                – I wrestled a bear once.
                9 hours ago












              • NOICE! Thanks bearman :D

                – Alireza
                9 hours ago













              2












              2








              2







              This is a solution with time complexity of O(n) where n is the number of elements in your array.



              Using the filter method as the OP wants it:






               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





              My personal preference here is to use ForEach as it looks more readable.






              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);





              We are using a Set and a simple combination of the elements of the array to make sure they are unique. Otherwise this would become O(n^2).






              share|improve this answer















              This is a solution with time complexity of O(n) where n is the number of elements in your array.



              Using the filter method as the OP wants it:






               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





              My personal preference here is to use ForEach as it looks more readable.






              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);





              We are using a Set and a simple combination of the elements of the array to make sure they are unique. Otherwise this would become O(n^2).






               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





               const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();


              const res = x.filter(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              return true;

              return false
              )

              console.log(res)





              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);





              const x = [[1, 2], [3, 4], [1, 2], [2, 1]];
              const s = new Set();
              const res = [];

              x.forEach(el =>
              if(!s.has(el.join("")))
              s.add(el.join(""));
              res.push(el)

              )

              console.log(res);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 9 hours ago

























              answered 9 hours ago









              AlirezaAlireza

              3871 silver badge9 bronze badges




              3871 silver badge9 bronze badges










              • 1





                @DominikMatis Added a solution with filter.

                – Alireza
                9 hours ago











              • what is the inner array is more than two elements?

                – I wrestled a bear once.
                9 hours ago











              • if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

                – Alireza
                9 hours ago






              • 1





                it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

                – I wrestled a bear once.
                9 hours ago












              • NOICE! Thanks bearman :D

                – Alireza
                9 hours ago












              • 1





                @DominikMatis Added a solution with filter.

                – Alireza
                9 hours ago











              • what is the inner array is more than two elements?

                – I wrestled a bear once.
                9 hours ago











              • if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

                – Alireza
                9 hours ago






              • 1





                it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

                – I wrestled a bear once.
                9 hours ago












              • NOICE! Thanks bearman :D

                – Alireza
                9 hours ago







              1




              1





              @DominikMatis Added a solution with filter.

              – Alireza
              9 hours ago





              @DominikMatis Added a solution with filter.

              – Alireza
              9 hours ago













              what is the inner array is more than two elements?

              – I wrestled a bear once.
              9 hours ago





              what is the inner array is more than two elements?

              – I wrestled a bear once.
              9 hours ago













              if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

              – Alireza
              9 hours ago





              if it's dynamic, we have to add another level of loop but this is still faster than a nested loop that works on the whole array twice. This would become O(n*m) where n === arr.length and m===arr[0].length, assuming that they are of the same length.

              – Alireza
              9 hours ago




              1




              1





              it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

              – I wrestled a bear once.
              9 hours ago






              it doesn't require another loop. consider changing el[0]+""+el[1] to el.join("") see array.join.

              – I wrestled a bear once.
              9 hours ago














              NOICE! Thanks bearman :D

              – Alireza
              9 hours ago





              NOICE! Thanks bearman :D

              – Alireza
              9 hours ago











              1














              The equivalent to



              x.filter((value,index,self) => (self.indexOf(value) === index))


              would be



              x.filter((v,i,self) => 
              for1:
              for (let j = 0; j < self.length; j++)
              if (i == j)
              return true;

              if (self[j].length != v.length)
              continue;

              for (let k = 0; k < v.length; k++)
              if (self[j][k] != v[k])
              continue for1;


              return false;

              return true;
              )


              Unlike some of the other answers, this does not require a conversion to string and can thus work with more complex values.
              Use === instead of == if you want.



              The time complexity is not great, of course.






              share|improve this answer

























              • solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

                – I wrestled a bear once.
                8 hours ago












              • So you are saying it is not equivalent, because your version actually works?

                – Bergi
                39 mins ago











              • @Iwrestledabearonce. self is totally fine as a local variable name.

                – Bergi
                39 mins ago











              • Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

                – Bergi
                37 mins ago















              1














              The equivalent to



              x.filter((value,index,self) => (self.indexOf(value) === index))


              would be



              x.filter((v,i,self) => 
              for1:
              for (let j = 0; j < self.length; j++)
              if (i == j)
              return true;

              if (self[j].length != v.length)
              continue;

              for (let k = 0; k < v.length; k++)
              if (self[j][k] != v[k])
              continue for1;


              return false;

              return true;
              )


              Unlike some of the other answers, this does not require a conversion to string and can thus work with more complex values.
              Use === instead of == if you want.



              The time complexity is not great, of course.






              share|improve this answer

























              • solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

                – I wrestled a bear once.
                8 hours ago












              • So you are saying it is not equivalent, because your version actually works?

                – Bergi
                39 mins ago











              • @Iwrestledabearonce. self is totally fine as a local variable name.

                – Bergi
                39 mins ago











              • Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

                – Bergi
                37 mins ago













              1












              1








              1







              The equivalent to



              x.filter((value,index,self) => (self.indexOf(value) === index))


              would be



              x.filter((v,i,self) => 
              for1:
              for (let j = 0; j < self.length; j++)
              if (i == j)
              return true;

              if (self[j].length != v.length)
              continue;

              for (let k = 0; k < v.length; k++)
              if (self[j][k] != v[k])
              continue for1;


              return false;

              return true;
              )


              Unlike some of the other answers, this does not require a conversion to string and can thus work with more complex values.
              Use === instead of == if you want.



              The time complexity is not great, of course.






              share|improve this answer













              The equivalent to



              x.filter((value,index,self) => (self.indexOf(value) === index))


              would be



              x.filter((v,i,self) => 
              for1:
              for (let j = 0; j < self.length; j++)
              if (i == j)
              return true;

              if (self[j].length != v.length)
              continue;

              for (let k = 0; k < v.length; k++)
              if (self[j][k] != v[k])
              continue for1;


              return false;

              return true;
              )


              Unlike some of the other answers, this does not require a conversion to string and can thus work with more complex values.
              Use === instead of == if you want.



              The time complexity is not great, of course.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 9 hours ago









              AndreaAndrea

              14.6k3 gold badges29 silver badges56 bronze badges




              14.6k3 gold badges29 silver badges56 bronze badges















              • solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

                – I wrestled a bear once.
                8 hours ago












              • So you are saying it is not equivalent, because your version actually works?

                – Bergi
                39 mins ago











              • @Iwrestledabearonce. self is totally fine as a local variable name.

                – Bergi
                39 mins ago











              • Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

                – Bergi
                37 mins ago

















              • solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

                – I wrestled a bear once.
                8 hours ago












              • So you are saying it is not equivalent, because your version actually works?

                – Bergi
                39 mins ago











              • @Iwrestledabearonce. self is totally fine as a local variable name.

                – Bergi
                39 mins ago











              • Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

                – Bergi
                37 mins ago
















              solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

              – I wrestled a bear once.
              8 hours ago






              solid answer, +1, but it doesn't work if the array contains objects whereas the json approaches do. also, self is reserved in javascript, ideally that should have a different name.

              – I wrestled a bear once.
              8 hours ago














              So you are saying it is not equivalent, because your version actually works?

              – Bergi
              39 mins ago





              So you are saying it is not equivalent, because your version actually works?

              – Bergi
              39 mins ago













              @Iwrestledabearonce. self is totally fine as a local variable name.

              – Bergi
              39 mins ago





              @Iwrestledabearonce. self is totally fine as a local variable name.

              – Bergi
              39 mins ago













              Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

              – Bergi
              37 mins ago





              Why use these overcomplicated loops instead of simply exchanging self.indexOf(value) for self.findIndex(x => x[0]==value[0] && x[1]==value[1]) (or even using every inside there if you want to support arbitrary-length arrays)?

              – Bergi
              37 mins ago











              1














              Effective solution:



              O(n) operations, where n is the length of x array



              O(n) memory space, where n is the length of x array






              const x = [[1, 2], [3, 4], [1, 2]];

              const arrayTable = Object.create(null);

              const uniqueArrays = x.filter(arr =>
              const arrStr = JSON.stringify(arr);

              if (!arrayTable[arrStr])
              arrayTable[arrStr] = true;
              return true;


              return false;
              );

              console.log(uniqueArrays);








              share|improve this answer








              New contributor



              akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.

























                1














                Effective solution:



                O(n) operations, where n is the length of x array



                O(n) memory space, where n is the length of x array






                const x = [[1, 2], [3, 4], [1, 2]];

                const arrayTable = Object.create(null);

                const uniqueArrays = x.filter(arr =>
                const arrStr = JSON.stringify(arr);

                if (!arrayTable[arrStr])
                arrayTable[arrStr] = true;
                return true;


                return false;
                );

                console.log(uniqueArrays);








                share|improve this answer








                New contributor



                akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.























                  1












                  1








                  1







                  Effective solution:



                  O(n) operations, where n is the length of x array



                  O(n) memory space, where n is the length of x array






                  const x = [[1, 2], [3, 4], [1, 2]];

                  const arrayTable = Object.create(null);

                  const uniqueArrays = x.filter(arr =>
                  const arrStr = JSON.stringify(arr);

                  if (!arrayTable[arrStr])
                  arrayTable[arrStr] = true;
                  return true;


                  return false;
                  );

                  console.log(uniqueArrays);








                  share|improve this answer








                  New contributor



                  akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  Effective solution:



                  O(n) operations, where n is the length of x array



                  O(n) memory space, where n is the length of x array






                  const x = [[1, 2], [3, 4], [1, 2]];

                  const arrayTable = Object.create(null);

                  const uniqueArrays = x.filter(arr =>
                  const arrStr = JSON.stringify(arr);

                  if (!arrayTable[arrStr])
                  arrayTable[arrStr] = true;
                  return true;


                  return false;
                  );

                  console.log(uniqueArrays);








                  const x = [[1, 2], [3, 4], [1, 2]];

                  const arrayTable = Object.create(null);

                  const uniqueArrays = x.filter(arr =>
                  const arrStr = JSON.stringify(arr);

                  if (!arrayTable[arrStr])
                  arrayTable[arrStr] = true;
                  return true;


                  return false;
                  );

                  console.log(uniqueArrays);





                  const x = [[1, 2], [3, 4], [1, 2]];

                  const arrayTable = Object.create(null);

                  const uniqueArrays = x.filter(arr =>
                  const arrStr = JSON.stringify(arr);

                  if (!arrayTable[arrStr])
                  arrayTable[arrStr] = true;
                  return true;


                  return false;
                  );

                  console.log(uniqueArrays);






                  share|improve this answer








                  New contributor



                  akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  share|improve this answer



                  share|improve this answer






                  New contributor



                  akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  answered 9 hours ago









                  akobbsakobbs

                  3057 bronze badges




                  3057 bronze badges




                  New contributor



                  akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.




                  New contributor




                  akobbs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.


























                      1














                      Filter just causes things to get into O(n^2).



                      The currently accepted answer uses .filter((itm, idx, arr) => arr.indexOf(itm) === idx) which will cause the array to be iterated each time during each iteration... n^2.



                      Why even go there? Not only that, you need to parse in the end. It is a lot of excess.



                      There is no real good way to filter without hitting O(n^2) here.



                      Instead, just use reduce. It is very straightforward and fast easily accomplishing O(n).



                      "Bin reduce the set to unique values."






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      If you were to have to go the route of filter, then n^2 must be used. You can iterate each item looking for existence using every.



                      "Keep every element which does not have a previous duplicate."






                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);








                      share|improve this answer

























                      • Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                        – Snorlite
                        5 hours ago















                      1














                      Filter just causes things to get into O(n^2).



                      The currently accepted answer uses .filter((itm, idx, arr) => arr.indexOf(itm) === idx) which will cause the array to be iterated each time during each iteration... n^2.



                      Why even go there? Not only that, you need to parse in the end. It is a lot of excess.



                      There is no real good way to filter without hitting O(n^2) here.



                      Instead, just use reduce. It is very straightforward and fast easily accomplishing O(n).



                      "Bin reduce the set to unique values."






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      If you were to have to go the route of filter, then n^2 must be used. You can iterate each item looking for existence using every.



                      "Keep every element which does not have a previous duplicate."






                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);








                      share|improve this answer

























                      • Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                        – Snorlite
                        5 hours ago













                      1












                      1








                      1







                      Filter just causes things to get into O(n^2).



                      The currently accepted answer uses .filter((itm, idx, arr) => arr.indexOf(itm) === idx) which will cause the array to be iterated each time during each iteration... n^2.



                      Why even go there? Not only that, you need to parse in the end. It is a lot of excess.



                      There is no real good way to filter without hitting O(n^2) here.



                      Instead, just use reduce. It is very straightforward and fast easily accomplishing O(n).



                      "Bin reduce the set to unique values."






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      If you were to have to go the route of filter, then n^2 must be used. You can iterate each item looking for existence using every.



                      "Keep every element which does not have a previous duplicate."






                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);








                      share|improve this answer













                      Filter just causes things to get into O(n^2).



                      The currently accepted answer uses .filter((itm, idx, arr) => arr.indexOf(itm) === idx) which will cause the array to be iterated each time during each iteration... n^2.



                      Why even go there? Not only that, you need to parse in the end. It is a lot of excess.



                      There is no real good way to filter without hitting O(n^2) here.



                      Instead, just use reduce. It is very straightforward and fast easily accomplishing O(n).



                      "Bin reduce the set to unique values."






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      If you were to have to go the route of filter, then n^2 must be used. You can iterate each item looking for existence using every.



                      "Keep every element which does not have a previous duplicate."






                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);








                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
                      let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),));
                      console.log(y);





                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);





                      let x = [
                      [1, 2],
                      [3, 4],
                      [1, 2],
                      [2, 1]
                      ];
                      let y = x.filter((lx, li) =>
                      x.every((rx, ri) =>
                      rx == lx ||
                      (JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
                      );
                      console.log(y);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 6 hours ago









                      Travis JTravis J

                      67k32 gold badges163 silver badges232 bronze badges




                      67k32 gold badges163 silver badges232 bronze badges















                      • Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                        – Snorlite
                        5 hours ago

















                      • Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                        – Snorlite
                        5 hours ago
















                      Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                      – Snorlite
                      5 hours ago





                      Thank you, could you please explain me the logic behind the use of reduce? I don't understand the algorithm

                      – Snorlite
                      5 hours ago











                      0














                      indexOf does not work on identical instances of arrays/objects type elements within an array, as such arrays just hold references.



                      In filter function instance you get via parameter v (in below code) is not the same instance as stored in array, making indexOf unable to return the index of it.



                      In below code, by converting objects to strings we can use indexOf to find duplicates.






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );








                      share|improve this answer



























                      • indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                        – I wrestled a bear once.
                        9 hours ago











                      • not if its an array of arrays, you cant find index of an array within an array using indexOf

                        – Akash Shrivastava
                        9 hours ago











                      • if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                        – I wrestled a bear once.
                        9 hours ago











                      • you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                        – Akash Shrivastava
                        9 hours ago






                      • 1





                        i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                        – I wrestled a bear once.
                        8 hours ago















                      0














                      indexOf does not work on identical instances of arrays/objects type elements within an array, as such arrays just hold references.



                      In filter function instance you get via parameter v (in below code) is not the same instance as stored in array, making indexOf unable to return the index of it.



                      In below code, by converting objects to strings we can use indexOf to find duplicates.






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );








                      share|improve this answer



























                      • indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                        – I wrestled a bear once.
                        9 hours ago











                      • not if its an array of arrays, you cant find index of an array within an array using indexOf

                        – Akash Shrivastava
                        9 hours ago











                      • if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                        – I wrestled a bear once.
                        9 hours ago











                      • you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                        – Akash Shrivastava
                        9 hours ago






                      • 1





                        i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                        – I wrestled a bear once.
                        8 hours ago













                      0












                      0








                      0







                      indexOf does not work on identical instances of arrays/objects type elements within an array, as such arrays just hold references.



                      In filter function instance you get via parameter v (in below code) is not the same instance as stored in array, making indexOf unable to return the index of it.



                      In below code, by converting objects to strings we can use indexOf to find duplicates.






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );








                      share|improve this answer















                      indexOf does not work on identical instances of arrays/objects type elements within an array, as such arrays just hold references.



                      In filter function instance you get via parameter v (in below code) is not the same instance as stored in array, making indexOf unable to return the index of it.



                      In below code, by converting objects to strings we can use indexOf to find duplicates.






                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );








                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );





                      let x = [[1, 2], [3, 4], [1, 2], [2, 1]];

                      console.log(x.
                      map(function(v)
                      return JSON.stringify(v)
                      )
                      .filter(function(v, i, o)
                      return o.length == i ? true : o.slice(i + 1).indexOf(v) == -1;
                      )
                      .map(function(v)
                      return JSON.parse(v)
                      )
                      );






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 8 hours ago

























                      answered 9 hours ago









                      Akash ShrivastavaAkash Shrivastava

                      1396 bronze badges




                      1396 bronze badges















                      • indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                        – I wrestled a bear once.
                        9 hours ago











                      • not if its an array of arrays, you cant find index of an array within an array using indexOf

                        – Akash Shrivastava
                        9 hours ago











                      • if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                        – I wrestled a bear once.
                        9 hours ago











                      • you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                        – Akash Shrivastava
                        9 hours ago






                      • 1





                        i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                        – I wrestled a bear once.
                        8 hours ago

















                      • indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                        – I wrestled a bear once.
                        9 hours ago











                      • not if its an array of arrays, you cant find index of an array within an array using indexOf

                        – Akash Shrivastava
                        9 hours ago











                      • if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                        – I wrestled a bear once.
                        9 hours ago











                      • you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                        – Akash Shrivastava
                        9 hours ago






                      • 1





                        i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                        – I wrestled a bear once.
                        8 hours ago
















                      indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                      – I wrestled a bear once.
                      9 hours ago





                      indexof works perfectly fine on arrays. jsbin.com/qerubadoqo/edit?js,console

                      – I wrestled a bear once.
                      9 hours ago













                      not if its an array of arrays, you cant find index of an array within an array using indexOf

                      – Akash Shrivastava
                      9 hours ago





                      not if its an array of arrays, you cant find index of an array within an array using indexOf

                      – Akash Shrivastava
                      9 hours ago













                      if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                      – I wrestled a bear once.
                      9 hours ago





                      if you took 15 seconds to click on the link i gave you would see that that statement is 100% incorrect. indexof works perfectly fine with arrays.

                      – I wrestled a bear once.
                      9 hours ago













                      you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                      – Akash Shrivastava
                      9 hours ago





                      you passed a reference in indexOf, not an array, try replacing 'a' with [2, 3] and see if it works

                      – Akash Shrivastava
                      9 hours ago




                      1




                      1





                      i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                      – I wrestled a bear once.
                      8 hours ago





                      i removed my vote but your explanation is still not accurate. indexOf does "work" on arrays, but it doens't search for identical arrays, it's searches for the exact instance of the array you tell it to search for. you're on the right track using the word "reference" though.

                      – I wrestled a bear once.
                      8 hours ago

















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57562611%2fhow-to-get-distinct-values-from-an-array-of-arrays-in-javascript-using-the-filte%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單