Filter JavaScript array without keys












0















I have a two dimensional array:



array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]


I would like to filter by country and return all the animals "associated" with that country in another array.



For example filtering by Kenya places dog and cat into another array.



Hope that makes sense. Any help would be most appreciated. Thanks.










share|improve this question


















  • 4





    do you have tried something? please add your code.

    – Nina Scholz
    Nov 22 '18 at 9:50






  • 1





    Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

    – T.J. Crowder
    Nov 22 '18 at 9:50
















0















I have a two dimensional array:



array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]


I would like to filter by country and return all the animals "associated" with that country in another array.



For example filtering by Kenya places dog and cat into another array.



Hope that makes sense. Any help would be most appreciated. Thanks.










share|improve this question


















  • 4





    do you have tried something? please add your code.

    – Nina Scholz
    Nov 22 '18 at 9:50






  • 1





    Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

    – T.J. Crowder
    Nov 22 '18 at 9:50














0












0








0


0






I have a two dimensional array:



array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]


I would like to filter by country and return all the animals "associated" with that country in another array.



For example filtering by Kenya places dog and cat into another array.



Hope that makes sense. Any help would be most appreciated. Thanks.










share|improve this question














I have a two dimensional array:



array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]


I would like to filter by country and return all the animals "associated" with that country in another array.



For example filtering by Kenya places dog and cat into another array.



Hope that makes sense. Any help would be most appreciated. Thanks.







javascript arrays filtering






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 9:48









user142553user142553

143




143








  • 4





    do you have tried something? please add your code.

    – Nina Scholz
    Nov 22 '18 at 9:50






  • 1





    Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

    – T.J. Crowder
    Nov 22 '18 at 9:50














  • 4





    do you have tried something? please add your code.

    – Nina Scholz
    Nov 22 '18 at 9:50






  • 1





    Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

    – T.J. Crowder
    Nov 22 '18 at 9:50








4




4





do you have tried something? please add your code.

– Nina Scholz
Nov 22 '18 at 9:50





do you have tried something? please add your code.

– Nina Scholz
Nov 22 '18 at 9:50




1




1





Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

– T.J. Crowder
Nov 22 '18 at 9:50





Arrays have keys: We normally call them indexes. In your example, the country appears to always be at index 2.

– T.J. Crowder
Nov 22 '18 at 9:50












5 Answers
5






active

oldest

votes


















0














Assuming that your animal is always at index 1 you can use can use Array.prototype.filter()
and Array.prototype.map() to achieve this.



.filter() will "filter" your 2d array to only include arrays which have the country within it, then .map() will convert this 2d array to a 1d array by "replacing" all the inner arrays to be the animal (ie index 1).



See working example below:






const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
filterBy = "kenya", // The contry to filter by

animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

console.log(animals);








share|improve this answer





















  • 1





    Great that worked a treat.

    – user142553
    Nov 24 '18 at 14:33











  • @user142553 no worries, glad to help ;)

    – Nick Parsons
    Nov 24 '18 at 14:36



















0














You could filter the array and then map the wanted item.



This solution take the advantage of destructuring assignment, where an array is taken and the items gets a name.






var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
result = array
.filter(([,, country]) => country === "kenya")
.map(([, animal]) => animal)

console.log(result);








share|improve this answer































    0














    Looking at the code you have provided and considering that the country is always in index-2 and animals are in index-1 you can use a forEach() loop to get animals for that particular country.






    var array = [
    ["car", "dog", "kenya"],
    ["plane", "cat", "kenya"],
    ["boat", "mouse", "england"]
    ];
    var country = 'kenya';
    var animals = ;
    array.forEach((item) => {
    if (item[2] === country) {
    animals.push(item[1]);;
    }
    });
    console.log(animals);








    share|improve this answer































      0














      You can create a generic function which gets the index of what type you want to filter ('2' for countries) and the value you want to match ('kenya' for example)






      array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
      const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

      const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

      console.log(filter_by(FILTER_TYPE.country, 'kenya'))








      share|improve this answer

































        0














        Here in country kenya you can find the related animals, of that country.
        Let me know, if any changes require.



        array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
        array.map((data,i) => {
        data.map((dataKey)=>{
        if(dataKey === "kenya"){
        console.log(array[i])
        }
        })
        })





        share|improve this answer























          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%2f53428072%2ffilter-javascript-array-without-keys%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Assuming that your animal is always at index 1 you can use can use Array.prototype.filter()
          and Array.prototype.map() to achieve this.



          .filter() will "filter" your 2d array to only include arrays which have the country within it, then .map() will convert this 2d array to a 1d array by "replacing" all the inner arrays to be the animal (ie index 1).



          See working example below:






          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);








          share|improve this answer





















          • 1





            Great that worked a treat.

            – user142553
            Nov 24 '18 at 14:33











          • @user142553 no worries, glad to help ;)

            – Nick Parsons
            Nov 24 '18 at 14:36
















          0














          Assuming that your animal is always at index 1 you can use can use Array.prototype.filter()
          and Array.prototype.map() to achieve this.



          .filter() will "filter" your 2d array to only include arrays which have the country within it, then .map() will convert this 2d array to a 1d array by "replacing" all the inner arrays to be the animal (ie index 1).



          See working example below:






          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);








          share|improve this answer





















          • 1





            Great that worked a treat.

            – user142553
            Nov 24 '18 at 14:33











          • @user142553 no worries, glad to help ;)

            – Nick Parsons
            Nov 24 '18 at 14:36














          0












          0








          0







          Assuming that your animal is always at index 1 you can use can use Array.prototype.filter()
          and Array.prototype.map() to achieve this.



          .filter() will "filter" your 2d array to only include arrays which have the country within it, then .map() will convert this 2d array to a 1d array by "replacing" all the inner arrays to be the animal (ie index 1).



          See working example below:






          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);








          share|improve this answer















          Assuming that your animal is always at index 1 you can use can use Array.prototype.filter()
          and Array.prototype.map() to achieve this.



          .filter() will "filter" your 2d array to only include arrays which have the country within it, then .map() will convert this 2d array to a 1d array by "replacing" all the inner arrays to be the animal (ie index 1).



          See working example below:






          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);








          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);





          const array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]],
          filterBy = "kenya", // The contry to filter by

          animals = array.filter(arr => arr[2] == filterBy).map(elem => elem[1]);

          console.log(animals);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 26 '18 at 10:12

























          answered Nov 22 '18 at 9:52









          Nick ParsonsNick Parsons

          5,3722721




          5,3722721








          • 1





            Great that worked a treat.

            – user142553
            Nov 24 '18 at 14:33











          • @user142553 no worries, glad to help ;)

            – Nick Parsons
            Nov 24 '18 at 14:36














          • 1





            Great that worked a treat.

            – user142553
            Nov 24 '18 at 14:33











          • @user142553 no worries, glad to help ;)

            – Nick Parsons
            Nov 24 '18 at 14:36








          1




          1





          Great that worked a treat.

          – user142553
          Nov 24 '18 at 14:33





          Great that worked a treat.

          – user142553
          Nov 24 '18 at 14:33













          @user142553 no worries, glad to help ;)

          – Nick Parsons
          Nov 24 '18 at 14:36





          @user142553 no worries, glad to help ;)

          – Nick Parsons
          Nov 24 '18 at 14:36













          0














          You could filter the array and then map the wanted item.



          This solution take the advantage of destructuring assignment, where an array is taken and the items gets a name.






          var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
          result = array
          .filter(([,, country]) => country === "kenya")
          .map(([, animal]) => animal)

          console.log(result);








          share|improve this answer




























            0














            You could filter the array and then map the wanted item.



            This solution take the advantage of destructuring assignment, where an array is taken and the items gets a name.






            var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
            result = array
            .filter(([,, country]) => country === "kenya")
            .map(([, animal]) => animal)

            console.log(result);








            share|improve this answer


























              0












              0








              0







              You could filter the array and then map the wanted item.



              This solution take the advantage of destructuring assignment, where an array is taken and the items gets a name.






              var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
              result = array
              .filter(([,, country]) => country === "kenya")
              .map(([, animal]) => animal)

              console.log(result);








              share|improve this answer













              You could filter the array and then map the wanted item.



              This solution take the advantage of destructuring assignment, where an array is taken and the items gets a name.






              var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
              result = array
              .filter(([,, country]) => country === "kenya")
              .map(([, animal]) => animal)

              console.log(result);








              var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
              result = array
              .filter(([,, country]) => country === "kenya")
              .map(([, animal]) => animal)

              console.log(result);





              var array = [["car", "dog", "kenya"], ["plane", "cat", "kenya"], ["boat", "mouse", "england"]],
              result = array
              .filter(([,, country]) => country === "kenya")
              .map(([, animal]) => animal)

              console.log(result);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 22 '18 at 9:52









              Nina ScholzNina Scholz

              180k1493160




              180k1493160























                  0














                  Looking at the code you have provided and considering that the country is always in index-2 and animals are in index-1 you can use a forEach() loop to get animals for that particular country.






                  var array = [
                  ["car", "dog", "kenya"],
                  ["plane", "cat", "kenya"],
                  ["boat", "mouse", "england"]
                  ];
                  var country = 'kenya';
                  var animals = ;
                  array.forEach((item) => {
                  if (item[2] === country) {
                  animals.push(item[1]);;
                  }
                  });
                  console.log(animals);








                  share|improve this answer




























                    0














                    Looking at the code you have provided and considering that the country is always in index-2 and animals are in index-1 you can use a forEach() loop to get animals for that particular country.






                    var array = [
                    ["car", "dog", "kenya"],
                    ["plane", "cat", "kenya"],
                    ["boat", "mouse", "england"]
                    ];
                    var country = 'kenya';
                    var animals = ;
                    array.forEach((item) => {
                    if (item[2] === country) {
                    animals.push(item[1]);;
                    }
                    });
                    console.log(animals);








                    share|improve this answer


























                      0












                      0








                      0







                      Looking at the code you have provided and considering that the country is always in index-2 and animals are in index-1 you can use a forEach() loop to get animals for that particular country.






                      var array = [
                      ["car", "dog", "kenya"],
                      ["plane", "cat", "kenya"],
                      ["boat", "mouse", "england"]
                      ];
                      var country = 'kenya';
                      var animals = ;
                      array.forEach((item) => {
                      if (item[2] === country) {
                      animals.push(item[1]);;
                      }
                      });
                      console.log(animals);








                      share|improve this answer













                      Looking at the code you have provided and considering that the country is always in index-2 and animals are in index-1 you can use a forEach() loop to get animals for that particular country.






                      var array = [
                      ["car", "dog", "kenya"],
                      ["plane", "cat", "kenya"],
                      ["boat", "mouse", "england"]
                      ];
                      var country = 'kenya';
                      var animals = ;
                      array.forEach((item) => {
                      if (item[2] === country) {
                      animals.push(item[1]);;
                      }
                      });
                      console.log(animals);








                      var array = [
                      ["car", "dog", "kenya"],
                      ["plane", "cat", "kenya"],
                      ["boat", "mouse", "england"]
                      ];
                      var country = 'kenya';
                      var animals = ;
                      array.forEach((item) => {
                      if (item[2] === country) {
                      animals.push(item[1]);;
                      }
                      });
                      console.log(animals);





                      var array = [
                      ["car", "dog", "kenya"],
                      ["plane", "cat", "kenya"],
                      ["boat", "mouse", "england"]
                      ];
                      var country = 'kenya';
                      var animals = ;
                      array.forEach((item) => {
                      if (item[2] === country) {
                      animals.push(item[1]);;
                      }
                      });
                      console.log(animals);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 22 '18 at 9:55









                      Ankit AgarwalAnkit Agarwal

                      23.8k52044




                      23.8k52044























                          0














                          You can create a generic function which gets the index of what type you want to filter ('2' for countries) and the value you want to match ('kenya' for example)






                          array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                          const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                          const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                          console.log(filter_by(FILTER_TYPE.country, 'kenya'))








                          share|improve this answer






























                            0














                            You can create a generic function which gets the index of what type you want to filter ('2' for countries) and the value you want to match ('kenya' for example)






                            array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                            const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                            const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                            console.log(filter_by(FILTER_TYPE.country, 'kenya'))








                            share|improve this answer




























                              0












                              0








                              0







                              You can create a generic function which gets the index of what type you want to filter ('2' for countries) and the value you want to match ('kenya' for example)






                              array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                              const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                              const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                              console.log(filter_by(FILTER_TYPE.country, 'kenya'))








                              share|improve this answer















                              You can create a generic function which gets the index of what type you want to filter ('2' for countries) and the value you want to match ('kenya' for example)






                              array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                              const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                              const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                              console.log(filter_by(FILTER_TYPE.country, 'kenya'))








                              array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                              const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                              const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                              console.log(filter_by(FILTER_TYPE.country, 'kenya'))





                              array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                              const FILTER_TYPE = { vehicle: 0, animal: 1, country: 2 }

                              const filter_by = (index, value) => (array.filter(item => (item[index] === value)).map(item => item[FILTER_TYPE.animal]))

                              console.log(filter_by(FILTER_TYPE.country, 'kenya'))






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 22 '18 at 10:02

























                              answered Nov 22 '18 at 9:52









                              omri_saadonomri_saadon

                              7,00541444




                              7,00541444























                                  0














                                  Here in country kenya you can find the related animals, of that country.
                                  Let me know, if any changes require.



                                  array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                                  array.map((data,i) => {
                                  data.map((dataKey)=>{
                                  if(dataKey === "kenya"){
                                  console.log(array[i])
                                  }
                                  })
                                  })





                                  share|improve this answer




























                                    0














                                    Here in country kenya you can find the related animals, of that country.
                                    Let me know, if any changes require.



                                    array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                                    array.map((data,i) => {
                                    data.map((dataKey)=>{
                                    if(dataKey === "kenya"){
                                    console.log(array[i])
                                    }
                                    })
                                    })





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Here in country kenya you can find the related animals, of that country.
                                      Let me know, if any changes require.



                                      array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                                      array.map((data,i) => {
                                      data.map((dataKey)=>{
                                      if(dataKey === "kenya"){
                                      console.log(array[i])
                                      }
                                      })
                                      })





                                      share|improve this answer













                                      Here in country kenya you can find the related animals, of that country.
                                      Let me know, if any changes require.



                                      array = [["car","dog","kenya"],["plane", "cat", "kenya"],["boat", "mouse", "england"]]
                                      array.map((data,i) => {
                                      data.map((dataKey)=>{
                                      if(dataKey === "kenya"){
                                      console.log(array[i])
                                      }
                                      })
                                      })






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 22 '18 at 10:14









                                      Anupam MauryaAnupam Maurya

                                      868




                                      868






























                                          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%2f53428072%2ffilter-javascript-array-without-keys%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

                                          Tonle Sap (See)

                                          I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                          Guatemaltekische Davis-Cup-Mannschaft