JavaScript Array Examples

Short summary:

Array from()Creates a new array instance from a series of similar or from a renewable object.
Array isArray()Checks the array.
Array of()Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
Array copyWithin()Copies a sequence of array elements within the array.
Array fill()Fills all the elements of an array from a start index to an end index with a static value.
Array pop()Removes the last element from an array and returns that element.
Array push()Adds one or more elements to the end of an array and returns the new length of the array.
Array reverse()Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
Array shift()Removes the first element from an array and returns that element.
Array sort()Sorts the elements of an array in place and returns the array.
Array splice()Adds and/or removes elements from an array.
Array concat()Returns a new array comprised of this array joined with other array(s) and/or value(s).
Array includes()Determines whether an array contains a certain element, returning true or false as appropriate.
Array slice()Extracts a section of an array and returns a new array.
Array indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Array lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Array entries()“entries()”method returns a new Array Iterator object. The object contains the entries for each item in the Array, and can be advanced with next().
Array every()“Every” function checks whether all the elements of the array satisfy the given condition or not that is provided by a function passed to it as the argument.
Array filter()
filter () returns data that satisfies the given conditions. 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.
Array find()The find () method searches for the specified value in the array. Returns the first providing value.
Array findIndex()FindIndex () returns the order of the first value that provides the condition in the array. In this respect, it is very similar to the find () method. The only difference between them: one turns the order and the other returns the value. Returns -1 if no value is entered.
Array flat()The flat() method available on the Array prototype returns a new array that’s a flattened version of the array it was called on. The default value(if no value is entered) is 1 .
Array forEach()The forEach () method is used to execute a function on each element in an array. In other words: forEach (), the ForEach () method runs a function once provided for each array element.
Array join()The Array.join () method combines elements in the array. The elements of the array are separated by the mark we give. If we don’t give any signs, it throws the “,” sign.
Array keys()The keys() method returns a new Array Iterator object that contains the keys for each index in the array.
Array flatMap()The flatMap () method maps each value to a new value, and then returns the resulting array to a maximum depth of 1.
Array map()The Map () method scans through each element of the array. It returns a new array with the elements it scans. The map() method calls the provided function once for each element in an array, in order.
Array reduce()The reduce () method reduces the array to a single value. executes a function provided from left to right for each value of the array. reduce() does not execute the function for array elements without values.
Array some()The some () method scans each element in the array, respectively. Ends scanning when the desired condition is met. Returns true. Returns false if the condition is not satisfied until the last element.

Example 1:

        let number = "1234567890";
        console.log(Array.from(number));

[“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “0”]


Example 2:

        let names = [["alex"],["john"],["bob"],["rick"]];
        let arr = Array.from(names);
        console.log(arr)

0: [“alex”]
1: [“john”]
2: [“bob”]
3: [“rick”]


Example 3:

        let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        let procces = Array.from(numbers,x => x*x);
        
        console.log(procces)

[1, 4, 9, 16, 25, 36, 49, 64, 81]


Example 4:

        let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        let procces = Array.from(numbers, x => x * x);
        procces.map((num) => {
            if (num % 2 == 0) {
                console.log("Solid of 2:" + num)
            }
        })

        procces.map((num) => {
            if (num % 3 == 0) {
                console.log("Solid of 3:" + num)
            }
        })
        
        procces.map((num) => {
            if (num % 5 == 0) {
                console.log("Solid of 5:" + num)
            }
        })

        procces.map((num) => {
            if (num % 7 == 0) {
                console.log("Solid of 7:" + num)
            }
        })

Solid of 2 : 4
Solid of 2 : 16
Solid of 2 : 36
Solid of 2 : 64
Solid of 3 : 9
Solid of 3 : 36
Solid of 3 : 81
Solid of 5 : 25
Solid of 7 : 49


Example 5:

isArray
    <div class="container">
        <h2>is Array?</h2>
        <select>
            <option id="number">Number</option>
            <option id="string">String</option>
            <option id="object">Object</option>
            <option id="undifined">Undifined</option>
            <option id="tru">True</option>
            <option id="fal">False</option>
        </select>
        <button onclick="show()">SHOW</button>
    </div>

    <script>

        function show() {
            if (number.selected) {
                alert("Yes. It's a array.")
            } else if (string.selected) {
                alert("No. It's not a array.")
            } else if (object.selected) {
                alert("Yes. It's a array.")
            } else if (undifined.selected) {
                alert("No. It's not a array.")
            } else if (tru.selected) {
                alert("No. It's not a array.")
            } else if (fal.selected) {
                alert("No. It's not a array.")
            }
        }
       
    </script>

Example 6

        let arr = ("john", "alex", "rihanna", "oliver");
        console.log(typeof (arr));

        console.log(typeof (Array.of(arr)));

string
object

The array is an object.


Example 7

        let carList = ["bmw", "audi", "mercedes", "range rover", "toyota", "tesla"];
        console.log("car list: " + carList);

        let sold = carList.fill("sold", 2, 5);
        console.log("new car list: " + carList);

car list: bmw, audi, mercedes, range rover, toyota, tesla
new car list: bmw, audi, sold, sold, sold, tesla


Example 8

javascript array example
    <div class="container">
        <input type="text" id="txt" />
        <button onclick="ext()">LAST ELEMENT REMOVE</button>
        <button onclick="add();">LAST ELEMENT ADD</button>
        <button onclick="show();">SHOW</button>
        <p id="result"></p>
    </div>


    <script>


        var list = ["rick","bob","alex","barry"]
        var res = document.querySelector("#result");

        function ext() {
            list.pop();
        }
        
        function add() {
            var txt = document.querySelector("#txt").value
            list.push(String(txt));
        }

        function show() {
            res.innerHTML = list;
        }


    </script>

Example 9

javascript array example
    <button onclick="reverse();">REVERSE</button>
    <button onclick="show();">SHOW</button>
    <p id="res"></p>

    <script>

        let res = document.getElementById("res");

        list = ["first", "second", "third", "forth", "fifth", "sixth"];

        function show() {
            res.innerHTML = list;
        }

        function reverse() {
            list.reverse();
        }
        
    </script>

Example 10

javascript array example
    <button onclick="start()">remove(start)</button>
    <button onclick="end()">remove(end)</button>
    <button onclick="show();">SHOW</button>
    <p id="result"></p>

    <script>

        let res = document.getElementById("result");

        let list = ["bmw", "audi", "range rover", "toyota", "tesla"];

        function show() {
            res.innerHTML = list;
        }

        function start() {
            list.shift();
        }

        function end() {
            list.pop();
        }

    </script>

Example 11

javascript array example
    <div class="container">
        <input type="text" id="name" />
        <button onclick="add();">ADD</button>
        <button onclick="show();">SHOW</button>
        <p id="result"></p>
    </div>


    <script>

        var res = document.getElementById("result");

        nameList = [];

        function add() {
            let name = document.getElementById("name").value;
            nameList.push(name)
        }

        function show() {
            let arr = nameList.sort();
            res.innerHTML = arr.map(x => x + "<br>").join("")
        }

    </script>

Example 12

javascript array example
    <p id="list"></p>
    <input type="text" id="name" />
    <button onclick="add()">ADD</button>
    <button onclick="del()">DELETE</button>
    <button onclick="ref()">REFRESH</button>

    <script>

        let list = document.getElementById("list");
        let people = ["furkan", "zeynep", "hasan", "idil", "irem", "ece"];
        

        function ref() {
            list.innerHTML = people.join("<br>");
        }

        function add() {
            name = document.getElementById("name").value;
            people.push(name);
        }

        function del() {
            name = document.getElementById("name").value;
            arr = people.indexOf(name);
            deleteArr = people.splice(arr, 1);
        }



    </script>

Example 13

javascript array example
<style>
        input{
            border-radius:20px 0px 0px 20px;
            padding-left:10px;
            outline:none;
            border:2px solid #262626;
            color: #262626
        }
        button{
            border-radius:0px 20px 20px 0px;
            margin-left:-5px;
            background:#262626;
            border-color:#262626;
            color:#fff;
            outline:none;
            cursor:pointer;
        }
    </style>


<body>

    <input type="text" id="name" placeholder="animal type" />
    <button onclick="search();">SEARCH</button>    

    <script>

    
        let animals = ["dog", "cat", "horse", "monkey", "donkey", "rabbit"];
        

        function search() {
            let name = document.getElementById("name").value;
            if (animals.includes(name) == true) {
                alert("This animal is available in our system")
            } else {
                alert("This animal is not available in our system")
            }
        }


    </script>

</body>

Example 14

array example
    <div onclick="start();">SHOW</div>
    <input type="text" id="remove"/>
    <div id="show"></div>
    <div id="kaldir">Remove</div>
    <div id="result"></div>


<script>
        var list = ["furkan", "zeynep", "alex", "john", "maria", "jack", "ellan", "tony"]; 

        function start() {
            var row = ""; 
            for (var i = 0; i < list.length; i++) { 
               row += list[i]+"<br>"; 
            }
            document.getElementById("show").innerHTML = row;           
        }
     
        kaldir = document.getElementById("kaldir") 
        kaldir.onclick = function () {
            var name = document.getElementById("remove").value; 
            if (name == false) {
                alert("boş bırakma")
            }
            else if (list.includes(name) === true) {
                var sira = Number(list.indexOf(name));
                list.splice(sira,1); 
            } else if (list.includes(name) === false) {
                alert("böyle bir elaman yok")
            }
        }

    </script>

Example 15

        let cars = ["bmw", "audi", "toyota", "skoda"];
        let newCarsList = [];

        cars.forEach((x) => {
            newCarsList.push(x);
        })

        console.log(newCarsList)

output:

[“bmw”, “audi”, “toyota”, “skoda”]


One thought on “JavaScript Array Examples

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started