Advanced Array manipulation in JS

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Advanced array manipulation</title>
</head>
<body>
    <script>
        var array = [];
        var item6 = {
            name: "item6", value: "value6"
        };
 
        //Adding items
        array.push({
            name: "item1", value: "value1"
        }, {
            name: "item2", value: "value2"
        }, {
            name: "item3", value: "value3"
        }, {
            name: "item4", value: "value4"
        }, {
            name: "item5", value: "value5"
        }, item6);
 
        //Removing items with splice()
        //We are removing 1 item from index 2 (so we are removing item3)
        array.splice(2, 1);
 
        //Finding the index of an item with indexOf()
        //We are finding the index of item6
        var result = array.indexOf(item6);
 
        //Sorting by a custom function with sort()
        //We are sorting by item name descending
        //NOTE: if a sorting function is not provided the array will be sorted
        //by item ascending (only work with primitive items, so not in this case)
        var sortedArray = array.sort(function (item1, item2) {
            return item1.name < item2.name;
        });
 
        //Filtering by some criteria with filter()
        //We are filtering to have just the odd items
        var filteredArray = array.filter(function (item) {
            var itemNumber = parseInt(item.name[5]);
            return itemNumber % 2 == 1;
        });
 
        //Mapping to another array with map()
        //We are creating another array with a new description field = name + value
        var mappedArray = array.map(function (item) {
            return { name: item.name, value: item.value, description: item.name + " " + item.value };
        });
 
        //Reducing to a single value with reduce()
        //We are concatenating all the items' values
        //NOTE: the first time previousItem is the first item and currentItem is the second item
        //NOTE: from the second time previousItem is the result of the previous elaboration
        var reducedValue = array.reduce(function (previousItem, currentItem, index, array) {
            if (index == 1) {
                return previousItem.value + " " + currentItem.value;
            } else {
                return previousItem + " " + currentItem.value;
            }
        });
    </script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s