One place for hosting & domains

      Method

      split() String Method in JavaScript


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Sometimes you just need to take strings apart:

      var sentence = "Oh a cookie!"
      
      sentence.split(" ");
      
      // [ "Oh", "a", "cookie!" ]
      

      Syntax

      The trick is using the correct separator:

      myArray.split(separator);
      

      Common use case

      If you leave the separator blank, it will dissect each character.

      var pieces = sentence.split("");
      
      // [ "O", "h", " ", "a", " ", "c", "o", "o", "k", "i", "e", "!" ]
      

      Notice that the spaces stay in the resulting array because they were not used as the separator.

      Learn More

      split() is just one of several methods that help developers work with strings, to learn more see How To Index, Split, and Manipulate Strings in JavaScript



      Source link

      Using the Array.find Method in JavaScript


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      The JavaScript Array.find method is a convenient way to find and return the first occurence of an element in an array, under a defined testing function. When you want a single needle from the haystack, reach for find()!

      When to Use Array.find

      The function and syntax of find() is very much like the Array.filter method, except it only returns a single element. Another difference is when nothing is found, this method returns a value of undefined.

      So if you only need a single value, use find()! When you need to find/return multiple values, reach for filter() instead.

      How to Use Array.find

      Using find() is super easy! The only required parameter of this method is a testing function, and it can be as simple or complex as needed. In its most basic form:

      array.find(testingFunction); // that's it!
      

      Simple example:

      Here’s a simple example with an array of strings:

      const trees = [ 
        "birch", 
        "maple", 
        "oak", 
        "poplar" 
      ];
      
      const result = trees.find(tree => tree.startsWith("m"));
      
      // "maple"
      

      In non-shorthand, non-ES6 form:

      const result = trees.find(function(tree) {
        return tree.startsWith("m");
      });
      
      // "maple"
      

      Using with objects:

      We can use find() to easily search arrays of objects, too!

      const trees = [
        { name: "birch", count: 4 },
        { name: "maple", count: 5 },
        { name: "oak", count: 2 }
      ];
      
      const result = trees.find(tree => tree.name === "oak");
      
      // { name: "oak", count, 2 }
      
      

      Using the same example, notice if we use find() when a test has multiple results, we only get the first value found:

      const result = trees.find(tree => tree.count > 2);
      
      // { name: "birch", count: 4 }
      

      This is an instance where you should probably use filter() instead. See the difference?

      Tip: Separating the testing function

      Sometimes you’ll want to re-use the same find() test function in multiple places. In that case, it can be really helpful to create a separate testing function.

      Let’s demo this technique, expanding on our previous examples:

      const deciduous = [
        { name: "birch", count: 4 },
        { name: "maple", count: 5 },
        { name: "oak", count: 2 }
      ];
      
      const evergreens = [
        { name: "cedar", count: 2 },
        { name: "fir", count: 6 },
        { name: "pine", count: 3 }
      ];
      
      // our testing function
      const hasFiveOrMore = el => el.count >= 5;
      
      const decResult = deciduous.find(hasFiveOrMore);
      // { name: "maple", count: 5 }
      
      const evgResult = evergreens.find(hasFiveOrMore);
      // { name: "fir", count: 6 }
      

      Simple, but powerful! 💪

      Using the index parameter

      Like filter(), there is an optional index parameter we can use. Here’s one last example, using it as part of our testing function:

      const evergreens = [
        { name: "cedar", count: 2 },
        { name: "fir", count: 6 },
        { name: "pine", count: 3 }
      ];
      
      // suppose we need to skip the first element
      const result = evergreens.find((tree, i) => {
        if (tree.count > 1 && i !== 0) return true;
      });
      
      // { name: "fir", count: 6 }
      

      The index is probably not something you’ll need often — but it’s great to have available at times.

      Conclusion

      Array.find is a simple but incredibly useful method for searching JavaScript arrays. It’s one of several useful methods available on Arrays, for a more complete guide see How To Use Array Methods in JavaScript: Iteration Methods.

      Just remember: only use find when you want a single element returned, and that it returns undefined if nothing is found! Otherwise, use the filter method when you need multiple elements returned.



      Source link

      filter() Array Method in JavaScript


      Introduction

      The filter() Array method creates a new array with elements that fall under a given criteria from an existing array:

      var numbers = [1, 3, 6, 8, 11];
      
      var lucky = numbers.filter(function(number) {
        return number > 7;
      });
      
      // [ 8, 11 ]
      

      The example above takes the numbers array and returns a new filtered array with only those values that are greater than seven.

      Filter syntax

      var newArray = array.filter(function(item) {
        return condition;
      });
      

      The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.

      If the current item passes the condition, it gets sent to the new array.

      Filtering an array of objects

      A common use case of .filter() is with an array of objects through their properties:

      var heroes = [
          {name: “Batman”, franchise: “DC”},
          {name: “Ironman”, franchise: “Marvel”},
          {name: “Thor”, franchise: “Marvel”},
          {name: “Superman”, franchise: “DC”}
      ];
      
      var marvelHeroes =  heroes.filter(function(hero) {
          return hero.franchise == “Marvel”;
      });
      
      // [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]
      

      Additional Resources

      For more details on filter() see MDN Reference.

      Filter is only one of several iteration methods on Arrays in JavaScript, read How To Use Array Iteration Methods in JavaScript to learn about the other methods like map() and reduce().



      Source link