Select Page
JavaScript ES6+ : Array Feature Improvements
Jayman Pandya
Apr 23, 2020

Array.from() convert Objects, Node-lists to Arrays, so that you can use all the Array functions to iterate through the data.

<html>
    <head>
        
    </head>
    <body>
        <ul class="facilityDetails">
            <li>Olympic Size Pool</li>
            <li>Kids Friendly</li>
            <li>Life Guard</li>
        </ul>

        <script>
            //This will return NodeList
            const facilityDetails = document.querySelectorAll('.facilityDetails li');
            console.log(facilityDetails);

            //Using Array.from() will convert it to an Array
            const facilityDetailsArray = Array.from(document.querySelectorAll('.facilityDetails li'));
            console.log(facilityDetailsArray);
        </script>
    </body>
</html>

Array.of() allows you to pass arguments in the function which will be converted to an array.

<script>
    function listAllAmenities(){
        // This will print an Object
        console.log(arguments);
        // This will print an array
        console.log(Array.of(arguments));
    }
    listAllAmenities('Olympic Size Pool', 'Kids Friendly', 'Life Guard');
</script>

.find() lets you find items in an array and .findIndex() lets you find the index of items in an array

<script>
const assets = [
    {
        "assetId" : "SWMP001",
        "capacity" : "25 pax",
        "associatedWith" : "Club Oasis"
    },

    {
        "assetId" : "SWMP002",
        "capacity" : "10 pax",
        "associatedWith" : "Club Onyx"
    },

    {
        "assetId" : "SWMP003",
        "capacity" : "18 pax",
        "associatedWith" : "Club Jira"
    }
];

//Will return the item in the Array
const asset = assets.find(asset => asset.assetId === "SWMP001");
console.log(asset);

//Will return the position of the item in the Array
const assetIndex = assets.findIndex(asset => asset.assetId === "SWMP003");
console.log(assetIndex);

</script>

some() lets check whether the condition is true some of the items in an array

const childrenOnly = [3, 12, 9, 34, 99];

const findSomeChildren = childrenOnly.some(child => child <= 18);
console.log(findSomeChildren);

every() lets check whether the condition is true every item in an array

const childrenOnly = [3, 12, 9, 34, 99];

const findSomeChildren = childrenOnly.every(child => child <= 18);
console.log(findSomeChildren);

Peace ✌️

Let's Talk

If you liked what you have seen, then let’s connect and make something amazing together.

Email me at converse@jaymanpandya.com or send a DM on my twitter @jaymanpandya