Can't get function to find multiple indexes of identical string in array

Multi tool use
Multi tool use












-2















I found this indexOf-Tryit on W3schools and decided to try modifying it into a function that finds index values for each instance of "Apple" and outputs them to a paragraph. I cannot get it to work and it's driving me mad.



I've tried using for and while-loops with many different variations.



function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

for (i=0; i < fruits.length; i++) {

if (fruits[i] = fruits.indexOf("Apple")) {
document.getElementById("demo").innerHTML += fruits[i];
} else {
document.getElementById("demo").innerHTML += "x"}
}
}


I want the paragraph to display "0x2x45xx8x10" or "0245810" without the else-operation. What I get instead is "x224458881010".










share|improve this question

























  • Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

    – Chris G
    Dec 30 '18 at 20:30











  • Why should I not use W3schools? Please elaborate.

    – user62840
    Dec 31 '18 at 11:59











  • meta.stackoverflow.com/questions/280478/why-not-w3schools-com

    – Chris G
    Dec 31 '18 at 12:01
















-2















I found this indexOf-Tryit on W3schools and decided to try modifying it into a function that finds index values for each instance of "Apple" and outputs them to a paragraph. I cannot get it to work and it's driving me mad.



I've tried using for and while-loops with many different variations.



function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

for (i=0; i < fruits.length; i++) {

if (fruits[i] = fruits.indexOf("Apple")) {
document.getElementById("demo").innerHTML += fruits[i];
} else {
document.getElementById("demo").innerHTML += "x"}
}
}


I want the paragraph to display "0x2x45xx8x10" or "0245810" without the else-operation. What I get instead is "x224458881010".










share|improve this question

























  • Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

    – Chris G
    Dec 30 '18 at 20:30











  • Why should I not use W3schools? Please elaborate.

    – user62840
    Dec 31 '18 at 11:59











  • meta.stackoverflow.com/questions/280478/why-not-w3schools-com

    – Chris G
    Dec 31 '18 at 12:01














-2












-2








-2








I found this indexOf-Tryit on W3schools and decided to try modifying it into a function that finds index values for each instance of "Apple" and outputs them to a paragraph. I cannot get it to work and it's driving me mad.



I've tried using for and while-loops with many different variations.



function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

for (i=0; i < fruits.length; i++) {

if (fruits[i] = fruits.indexOf("Apple")) {
document.getElementById("demo").innerHTML += fruits[i];
} else {
document.getElementById("demo").innerHTML += "x"}
}
}


I want the paragraph to display "0x2x45xx8x10" or "0245810" without the else-operation. What I get instead is "x224458881010".










share|improve this question
















I found this indexOf-Tryit on W3schools and decided to try modifying it into a function that finds index values for each instance of "Apple" and outputs them to a paragraph. I cannot get it to work and it's driving me mad.



I've tried using for and while-loops with many different variations.



function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

for (i=0; i < fruits.length; i++) {

if (fruits[i] = fruits.indexOf("Apple")) {
document.getElementById("demo").innerHTML += fruits[i];
} else {
document.getElementById("demo").innerHTML += "x"}
}
}


I want the paragraph to display "0x2x45xx8x10" or "0245810" without the else-operation. What I get instead is "x224458881010".







javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 20:26









Carcigenicate

17.6k43158




17.6k43158










asked Dec 30 '18 at 20:25









user62840user62840

61




61













  • Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

    – Chris G
    Dec 30 '18 at 20:30











  • Why should I not use W3schools? Please elaborate.

    – user62840
    Dec 31 '18 at 11:59











  • meta.stackoverflow.com/questions/280478/why-not-w3schools-com

    – Chris G
    Dec 31 '18 at 12:01



















  • Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

    – Chris G
    Dec 30 '18 at 20:30











  • Why should I not use W3schools? Please elaborate.

    – user62840
    Dec 31 '18 at 11:59











  • meta.stackoverflow.com/questions/280478/why-not-w3schools-com

    – Chris G
    Dec 31 '18 at 12:01

















Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

– Chris G
Dec 30 '18 at 20:30





Sounds like you want this: jsfiddle.net/khrismuc/wL8un027 (main issue: = is for assignment; for comparisons you need == or ===. And please don't use w3schools)

– Chris G
Dec 30 '18 at 20:30













Why should I not use W3schools? Please elaborate.

– user62840
Dec 31 '18 at 11:59





Why should I not use W3schools? Please elaborate.

– user62840
Dec 31 '18 at 11:59













meta.stackoverflow.com/questions/280478/why-not-w3schools-com

– Chris G
Dec 31 '18 at 12:01





meta.stackoverflow.com/questions/280478/why-not-w3schools-com

– Chris G
Dec 31 '18 at 12:01












2 Answers
2






active

oldest

votes


















1














Problem was if (fruits[i] = fruits.indexOf("Apple")) you're changing value of fruits[i]. Moreover you can directly compare the value and use the index as you're already looping through array.






function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

for (i=0; i < fruits.length; i++) {

if (fruits[i] === "Apple") {
document.getElementById("demo").innerHTML += i;
} else {
document.getElementById("demo").innerHTML += "x"}
}
}

myFunction()

<div id='demo'>
</div>








share|improve this answer

































    0














    Another approach is to map the string values to the index value if they match. If they don't match set a falsy value. Then use filter to remove all non matching values.



    Passing in the array to be searched and the value you're looking for makes the function more reusable. And not returning a string allows the function to more flexible still. It's easy enough to join an array with .join(',')






    function findIndexesOf(arr, value) {
    return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
    }

    let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


    let appleIndexs = findIndexesOf(fruits, "Apple")
    console.log("Apples:", appleIndexs.join(','))
    console.log(appleIndexs)


    let mangoIndexs = findIndexesOf(fruits, "Mango")
    console.log(mangoIndexs)








    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%2f53981154%2fcant-get-function-to-find-multiple-indexes-of-identical-string-in-array%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Problem was if (fruits[i] = fruits.indexOf("Apple")) you're changing value of fruits[i]. Moreover you can directly compare the value and use the index as you're already looping through array.






      function myFunction() {
      var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

      for (i=0; i < fruits.length; i++) {

      if (fruits[i] === "Apple") {
      document.getElementById("demo").innerHTML += i;
      } else {
      document.getElementById("demo").innerHTML += "x"}
      }
      }

      myFunction()

      <div id='demo'>
      </div>








      share|improve this answer






























        1














        Problem was if (fruits[i] = fruits.indexOf("Apple")) you're changing value of fruits[i]. Moreover you can directly compare the value and use the index as you're already looping through array.






        function myFunction() {
        var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

        for (i=0; i < fruits.length; i++) {

        if (fruits[i] === "Apple") {
        document.getElementById("demo").innerHTML += i;
        } else {
        document.getElementById("demo").innerHTML += "x"}
        }
        }

        myFunction()

        <div id='demo'>
        </div>








        share|improve this answer




























          1












          1








          1







          Problem was if (fruits[i] = fruits.indexOf("Apple")) you're changing value of fruits[i]. Moreover you can directly compare the value and use the index as you're already looping through array.






          function myFunction() {
          var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

          for (i=0; i < fruits.length; i++) {

          if (fruits[i] === "Apple") {
          document.getElementById("demo").innerHTML += i;
          } else {
          document.getElementById("demo").innerHTML += "x"}
          }
          }

          myFunction()

          <div id='demo'>
          </div>








          share|improve this answer















          Problem was if (fruits[i] = fruits.indexOf("Apple")) you're changing value of fruits[i]. Moreover you can directly compare the value and use the index as you're already looping through array.






          function myFunction() {
          var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

          for (i=0; i < fruits.length; i++) {

          if (fruits[i] === "Apple") {
          document.getElementById("demo").innerHTML += i;
          } else {
          document.getElementById("demo").innerHTML += "x"}
          }
          }

          myFunction()

          <div id='demo'>
          </div>








          function myFunction() {
          var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

          for (i=0; i < fruits.length; i++) {

          if (fruits[i] === "Apple") {
          document.getElementById("demo").innerHTML += i;
          } else {
          document.getElementById("demo").innerHTML += "x"}
          }
          }

          myFunction()

          <div id='demo'>
          </div>





          function myFunction() {
          var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];

          for (i=0; i < fruits.length; i++) {

          if (fruits[i] === "Apple") {
          document.getElementById("demo").innerHTML += i;
          } else {
          document.getElementById("demo").innerHTML += "x"}
          }
          }

          myFunction()

          <div id='demo'>
          </div>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 30 '18 at 20:38

























          answered Dec 30 '18 at 20:32









          Code ManiacCode Maniac

          4,6011219




          4,6011219

























              0














              Another approach is to map the string values to the index value if they match. If they don't match set a falsy value. Then use filter to remove all non matching values.



              Passing in the array to be searched and the value you're looking for makes the function more reusable. And not returning a string allows the function to more flexible still. It's easy enough to join an array with .join(',')






              function findIndexesOf(arr, value) {
              return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
              }

              let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


              let appleIndexs = findIndexesOf(fruits, "Apple")
              console.log("Apples:", appleIndexs.join(','))
              console.log(appleIndexs)


              let mangoIndexs = findIndexesOf(fruits, "Mango")
              console.log(mangoIndexs)








              share|improve this answer




























                0














                Another approach is to map the string values to the index value if they match. If they don't match set a falsy value. Then use filter to remove all non matching values.



                Passing in the array to be searched and the value you're looking for makes the function more reusable. And not returning a string allows the function to more flexible still. It's easy enough to join an array with .join(',')






                function findIndexesOf(arr, value) {
                return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
                }

                let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


                let appleIndexs = findIndexesOf(fruits, "Apple")
                console.log("Apples:", appleIndexs.join(','))
                console.log(appleIndexs)


                let mangoIndexs = findIndexesOf(fruits, "Mango")
                console.log(mangoIndexs)








                share|improve this answer


























                  0












                  0








                  0







                  Another approach is to map the string values to the index value if they match. If they don't match set a falsy value. Then use filter to remove all non matching values.



                  Passing in the array to be searched and the value you're looking for makes the function more reusable. And not returning a string allows the function to more flexible still. It's easy enough to join an array with .join(',')






                  function findIndexesOf(arr, value) {
                  return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
                  }

                  let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


                  let appleIndexs = findIndexesOf(fruits, "Apple")
                  console.log("Apples:", appleIndexs.join(','))
                  console.log(appleIndexs)


                  let mangoIndexs = findIndexesOf(fruits, "Mango")
                  console.log(mangoIndexs)








                  share|improve this answer













                  Another approach is to map the string values to the index value if they match. If they don't match set a falsy value. Then use filter to remove all non matching values.



                  Passing in the array to be searched and the value you're looking for makes the function more reusable. And not returning a string allows the function to more flexible still. It's easy enough to join an array with .join(',')






                  function findIndexesOf(arr, value) {
                  return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
                  }

                  let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


                  let appleIndexs = findIndexesOf(fruits, "Apple")
                  console.log("Apples:", appleIndexs.join(','))
                  console.log(appleIndexs)


                  let mangoIndexs = findIndexesOf(fruits, "Mango")
                  console.log(mangoIndexs)








                  function findIndexesOf(arr, value) {
                  return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
                  }

                  let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


                  let appleIndexs = findIndexesOf(fruits, "Apple")
                  console.log("Apples:", appleIndexs.join(','))
                  console.log(appleIndexs)


                  let mangoIndexs = findIndexesOf(fruits, "Mango")
                  console.log(mangoIndexs)





                  function findIndexesOf(arr, value) {
                  return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
                  }

                  let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];


                  let appleIndexs = findIndexesOf(fruits, "Apple")
                  console.log("Apples:", appleIndexs.join(','))
                  console.log(appleIndexs)


                  let mangoIndexs = findIndexesOf(fruits, "Mango")
                  console.log(mangoIndexs)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 30 '18 at 23:09









                  LexLex

                  2,05512341




                  2,05512341






























                      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%2f53981154%2fcant-get-function-to-find-multiple-indexes-of-identical-string-in-array%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







                      0Lk9zIDJ5tYO4Ag
                      BkF,p LSe4ZVIvwW zj2ObqfArY9TuL8b2T,cu rbAljUlc08s50Ua8Lws9,LHoS,qMNVg,X,KLf3,mc

                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas