Commonly Utilized JavaScript Methods III - Iteration Methods

 Welcome back to part 3 of the the Commonly Utilized JavaScript Methods series, in this article we shall cover the iteration methods. Iteration methods are integral for the means to perform repetition in a programming. For duties such as traversal through an array, to obtain a character, element or index upon condition passed. There are a plethora of iteration methods such forEach() - a mutator method which I've covered but there is also the .map(), .filter(),  .reduce(),  and .find(),  


What is the .map() method?

This method is responsible for the creation and return of a new array displaying each element of the original array, with or without manipulation displayed in new array. The map method is essentially a callback function, when the callback function is executed the new array is displayed. The callback function accepts 3 arguments which is - the element: The element or elements to be manipulated in the array, the index: the index of the element or elements to be manipulated as well as the the array: the array that is being manipulated. The index and array are optional arguments. It is ideal to only utilize the map method for when the new array data is going to be utilized. For cases of which it is not it is more ideal to utilize the .forEach() method or for of loop. There are a plethora of ways to implement and utilize the .map() method to produce an abundance of results which shall be displayed in the examples below.

Examples of .map() method:

//.map() method:

//Example 1- Printing each iteration via console.log:
let torontoZoo = ["Zebra", "Orangutan", "Chimpanzee", "Lion", "Ostrich"];

//printing iterations via console.log:
let printAnimals = torontoZoo.map((animals) => {
console.log(animals);
});
/*

Results:
Zebra
Orangutan
Chimpanzee
Lion
Ostrich

*/

//Example 2 - to implement s on the elements:
let pluralAnimals = torontoZoo.map((animals) => {
return `${animals}s`;
});
console.log(pluralAnimals);
//Results: [ 'Zebras', 'Orangutans', 'Chimpanzees', 'Lions', 'Ostrichs' ]

//Example 3 - multiplying numbers in original array:
let originalNumbers = [3, 6, 9, 12, 15];

let multiplyNumbers = (numberItem) => numberItem * 2;

//Calling map function:
let largeNumbers = originalNumbers.map(multiplyNumbers);

console.log(largeNumbers); //Results [ 6, 12, 18, 24, 30 ]

//Example 4 - converting a string into an array with each letter separated w/o use of split method:
const name = "Sublime";
//setting array via variable to append string to array:
const map = Array.prototype.map;

const addNameToArray = map.call(name, (eachLetter) => {
return `${eachLetter}`;
});

console.log(addNameToArray); /* Results: [
'S', 'u', 'b',
'l', 'i', 'm',
'e'
] */


What is the .reduce() method?

The reduce method is call back function utilized to produce the single value of an array without compromising/manipulating  the original array. This method is not exclusive to merely strings but can be applied to other data types such as numbers and is commonly utilized for  array with a number set providing a grand total sum, and things of that nature. The reduce methods accepts 4 arguments: the previousValue - value previous to the call being implemented, the currentValue - the value of current element, the currentIndex  and the object. For scenarios of previousValues and currentValue needing to be assessed and appended then it should be perceived as two values - 1. For an instance of initialValue being passed as argument then the initialValue is recognized as previousValue, then currentValue would be the first value the array being iterated. 2. For an instance of no initialValue passed, then previousValue is recognized as the first value in the array and currentValue will be deemed as second value in the array.

Examples of .reduce method:

//.reduce method:

//Example 1 - produce sum of values in an array:
let sumOfArray = [2, 4, 6, 8].reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
console.log(sumOfArray); //Results: 20

//Example 2 - obtaining sum of values in an object array:
{
/* Rule of thumb is that initialValue must be set to obtain sum for objects */
}
let initialValue = 0;

let sumOfObjects = [{ x: 4 }, { x: 8 }, { x: 12 }].reduce(function (
previousValue,
currentValue
) {
return previousValue + currentValue.x;
},
initialValue);

console.log(sumOfObjects); //Results: 24

//Example 3 - removal of subset in arrays/flattening array:
let noSubsetArrays = [
[2, 4],
[6, 8],
[10, 12],
].reduce(function (previousValue, currentValue) {
//using accessor method to piece together each element into one array:
return previousValue.concat(currentValue);
}, []);

console.log(noSubsetArrays); //Results: [ 2, 4, 6, 8, 10, 12 ]

//Example 4 - Implementing reduce method to group object via props:
let familyMembers = [
{ name: "LT", age: 56 },
{ name: "IA", age: 56 },
{ name: "Sublime", age: 27 },
{ name: "WY1", age: 25 },
{ name: "WY2", age: 21 },
];

//Initialization of reduce method via callback:
function groupByAge(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}

let groupedMembers = groupByAge(familyMembers, "age");
console.log(groupedMembers);
/*
Results:
{
'21': [ { name: 'WY2', age: 21 } ],
'25': [ { name: 'WY1', age: 25 } ],
'27': [ { name: 'Sublime', age: 27 } ],
'56': [ { name: 'LT', age: 56 }, { name: 'IA', age: 56 } ]
}
*/


What is the .find() method?

This method is responsible for returning value of element that matches the argument passed/test otherwise it would return undefined. When initialized via Arrow function arguments passes are element, index and array, for an instance of Callback function, the same arguments are passed as well with index and array being optional for both.

Examples of .find() method:

//.find() method:

//Example 1 - Find an object in an array via property:
const groceryShoppingList = [
{ item: "strawberries", quantity: 10 },
{ item: "bananas", quantity: 6 },
{ item: "apples", quantity: 8 },
{ item: "cranberries", quantity: 20 },
{ item: "pineapples", quantity: 30 },
{ item: "mangos", quantity: 4 },
];

//function to check and return inventory via name:
function isMangos(fruit) {
return fruit.item === "mangos";
}

console.log(groceryShoppingList.find(isMangos));
//Results: { item: 'mangos', quantity: 4 }

This concludes the article, the next entry shall be regarding loops.


Comments

Popular Posts