Saturday, March 9, 2019

Javascript: Array Helper Methods

forEach()

forEach() is usually used as a replacement for traditional for-loop. Lets add an array of numbers. In classic Javascript, this is how you will write the code:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

for (var i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum);

Using forEach helper method, the code will be something like below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

numbers.forEach(function(number) {
  sum += number;
});

console.log(sum);

The iterator function doesn't have to be an anonymous function. We can declare a function separately and then pass it in forEach as below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

function addNumbers(number) {
  sum += number;
}

numbers.forEach(addNumbers);

console.log(sum);

map()

Write a loop that iterates over a list of numbers, doubles the value of each number in the array and then pushes the doubled number into a new array.

In classic JS, this is how the code will look like:
var numbers = [11, 12, 13, 14, 15];

var double = [];

for (var i = 0; i < numbers.length; i++) {
  double.push(numbers[i] * 2);
}

console.log(double);

Now we will refactor the code above to use the map helper.
var numbers = [11, 12, 13, 14, 15];

var double = numbers.map(function(number) {
  return number * 2;
});

console.log(double);

You can also reformat the code like below:
var numbers = [11, 12, 13, 14, 15];

var doubleFn = (num) => num * 2;

var double = numbers.map(doubleFn);

console.log(double);

One of the most common uses of map is collecting properties of an array of object. Check the code below:
const persons = [
  {firstName:"John", lastName:"Doe"},
  {firstName:"Mike", lastName:"Crusoe"},
];

const firstNames = persons.map(person => person.firstName);

console.log(firstNames);

filter()

We will be filtering out persons who are working in Finance department. This is how we will write code in classic Javascript:
var persons = [
  {firstName:"John", lastName:"Doe", age:46, department:"Finance"},
  {firstName:"Mike", lastName:"Crusoe", age:40, department:"Finance"},
  {firstName:"Mary", lastName:"Jane", age:30, department:"HR"}
];

var filteredPersons = [];

for (var i = 0; i < persons.length; i++) {
  if (persons[i].department === "Finance") {
    filtered.push(persons[i]);
  }
}
console.log(filteredPersons);

Now we will refactor the code above to use the filter helper.
const persons = [
    { firstName: "John", lastName: "Doe", age: 46, department: "Finance" },
    { firstName: "Mike", lastName: "Crusoe", age: 40, department: "Finance" },
    { firstName: "Mary", lastName: "Jane", age: 30, department: "HR" }
];

const filteredPersons = persons.filter(person => person.department === 'Finance');

console.log(filteredPersons);

find()

This method will return only first element where callback function returns true; it don't process other elements.

We will search for user whose name is Mike. This is how we will write code in classic Javascript:
var users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

var user;

for (var i = 0; i < users.length; i++) {
  if (users[i].name === 'Mike') {
    user = users[i];
    break;
  }
}

console.log(user);

Now we will refactor the code above to use the find helper.
const users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

const user = users.find(user => user.name === 'Mike');

console.log(user);

Share This:    Facebook Twitter

1 comment:

  1. https://alligator.io/js/push-pop-shift-unshift-array-methods/
    https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/

    ReplyDelete

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top