JavaScript Array and its functions - map(), reduce() and filter()

JavaScript Array class is a global object that is used in the construction of arrays. Arrays are objects with additional methods and properties. Like Object Array can have indexed and non-index elements. Before discussing commonly used JS Array functions, let's see how Array is different from Object.

Create an array with two elements(or properties) : Two elements added to array are indexed element.

  let my_cart = ['Item1-Brush', 'Item2-Stove','Item3-Laptop']

Currently length of array my_cart is 3. Add to non-indexed element/properties to my_cart using dot & bracket notation.

 my_cart.nonIndexed_item4 = "Item4-Laptop"
 my_cart["nonIndexed_item5"] = "Item5-monitor"

After adding two non-indexed property length of Array my_cart is still 3. Why? - length property of array does not indicate how many elements are present in Array, length is numerically greater than the biggest array index.


How to find length of Array/total number of elements present in an array ? 
- Using Object.keys(my_cart).length

Array.prototype functions

Array.prototype.map() - Used to create a new array by passing a callback function. Callback is applied on every element in the array.
An array with numbers and fetch square of positive integers from the given array. Original array is not modified.
let numbers = [1, 2, 3, 4, 5]
let modifed_numbers = numbers.map(num => (num*num))
// modifed_numbers [1, 4, 9, 16, 25] //numbers [1, 2, 3, 4, 5]

Get a modified array of object using callback function
let check_out_items = [{
    item_id: 1001,
    quantity: 10,
    item_name: 'Apple',
    unit_price: .4
}, {
    item_id: 2001,
    quantity: 20,
    item_name: 'Orange',
    unit_price: .3
}, {
    item_id: 3001,
    quantity: 5,
    item_name: 'mango',
    unit_price: .7
}]
//print check_out_items
0: {item_id: 1001, quantity: 10, item_name: "Apple", unit_price: 0.4}
1: {item_id: 2001, quantity: 20, item_name: "Orange", unit_price: 0.3}
2: {item_id: 3001, quantity: 5, item_name: "mango", unit_price: 0.7}

let check_out_price = check_out_items.map(item => {
    let item_price = {}
    item_price[item.item_name] = (item.quantity * item.unit_price)
    return item_price
})
//print check_out_price
0: {Apple: 4}
1: {Orange: 6}
2: {mango: 3.5}

Use .map() method should be only used when modified array need to re-used, otherwise .forEach() will be right choice to iterate all array elements and perform operation. 

Array.prototype.reduce()
- reduce() method executes a reducer function on each element of the array and resulting in a single output value. Consider above array check_out_price and apply reduce method find total price need to be paid at checkout.
Sample reduce() function:
function (accumulator, currentValue) {
  return accumulator + currentValue
}, initialValue

let check_out_price = check_out_items.map(item => {
   return (item.quantity * item.unit_price)
})

// console.log(check_out_price) [4, 6, 3.5]

let total_price = check_out_price.reduce(function (accumulator, currentValue) {
    return accumulator + currentValue
}, 0)

//console.log(total_price) 13.5

Reduce function can be applied to an array with an initial Value or without initial Value. If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

Array.prototype.filter() - filter() method creates a new array with all elements that pass the test implemented by the callback function.
let input = [4, 5, 6, 8, 9, 12, 17];
//console.log(input) [4, 6, 8, 12]
let filtered_input = input.filter(num =>; num %2 ==0)
// let filtered_input = input.filter(function(num){return num %2 ==0})

//console.log(filtered_input) [4, 6, 8, 12]


2 Comments

Previous Post Next Post