Home  • Programming • JavaScript

Useful Array Functions: JavaScript

1. map() 2. forEach() 3. find() 4. filter() 5. sort() 6. reduce() 7. includes() 8. splice() 9. concat() 10. indexOf() 11. push() 12. pop() 13. shift() 14. unshift() 15. keys() 16. values() 17. join() 18. isArray() 19. at() 20. of() 21. reverse() 1 map()
<script>
        let names = ["Anayet", "Azmir", "Kamruzzaman", "Tasmin"];

        let html= names.map((n) => {
            return `$<div>{n}</div>`;
        });

        document.write(html);

    </script>
2 forEach()
<script>
  let names=["Anayet","Azmir","Kamruzzaman","Tasmin","Didar"];
        names.forEach((name,i)=>{
            document.write(name+"<br>");
        });
        document.write("Total: "+names.length);
</script>
3 find()
<script>
  let names=["Anayet","Azmir","Kamruzzaman","Tasmin","Didar"];
 let name = names.find((n) => {
                return n === search
            });
document.write(name);
</script>
4 filter()
<script>
    let names = ["Anayet", "Azmir", "Kamruzzaman", "Tasmin"];

    let name = "A";

    let short_list = names.filter((n) => {
      if (n.includes(name)) {
        return n;
      }
    });

    let short_list2 = names.filter((n) => {
      if (n.length > 6) {
        return n;
      }
    });
    document.write(short_list2);
  </script>
5 sort()
<script>
  let names=["Anayet","Azmir","Kamruzzaman","Tasmin","Didar"];
 let sorted = names.sort();
document.write(sorted);
</script>
6 reduce()
 <script>
        const array1 = [1, 2, 3, 4];        
        const init = 2;
        const sum = array1.reduce((total, next) => {
            return total + next
        }, init
        );

        document.write(sum);
       
    </script>
7 includes()
 <script>
    const pets = ['cat', 'dog', 'bat'];

    console.log(pets.includes('cat'));
   // Expected output: true

    console.log(pets.includes('at'));
    // Expected output: false

    </script>
8 splice()
 <script>
   // One parameter: remove all from length in the right hand side
        let nums = [1, 3, 5, 7];
        nums.splice(2);
        document.write(nums);


        document.write("<br>");

        // Two parameters: Remove items from array in the right hand side which number is defined in the second parameter from length in the first parameter
        let nums2 = [10, 11, 12, 13, 16];
        nums2.splice(2, 1);
        document.write(nums2);


        document.write("<br>");

        // Three parameters: insert or replace item according to the parameter
        let nums3 = [30, 31, 32, 33, 36];
        nums3.splice(2, 1,35);
        document.write(nums3);
    </script>
9 concat()
 <script>
   const array1 = ['a', 'b', 'c'];
   const array2 = ['d', 'e', 'f'];
   const array3 = array1.concat(array2);

   console.log(array3);
  // Expected output: Array ["a", "b", "c", "d", "e", "f"]

    </script>

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd