Posted in JavaScript, Useful Script

Javascript useful script [Part 1]

javascript

In this topic, I will provide some useful scripts in Javascript, they can help us a lot for coding

  1. Array
  • .filter()

Create a new array base on an existed array with filter conditions.

const studentAge= [17,16,18,19,21,15]
const ableToDrink = studentsAge.filter( age => age > 18 );
// Result: ableToDrink= [19,21]
  • .map()

Create a new array by copying and editing data of an existed array

// Example: create new array from numbers array and add '&' for each element
const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// Result: dollars = ['$2', '$3', '$4', '$5']
  • .forEach()

Do a certain action on each element in an array

const emotions = ['happy', 'sad', 'angry'];
emotions.forEach( emotion => console.log(emotion) );
// Result will disply one by one
// 'happy'
// 'sad'
// 'angry'
  • .some()

Check if any element in array satisfy a certain condition. If yes, return true, otherwise, return false.

 
const userPrivileges = ['user', 'user', 'user', 'admin'];
const containsAdmin = userPrivileges.some( element => element === 'admin');
// Result: containsAdmin = true, because array has element that contain 'admin'
  • .every()

Like ‘.some()’ function but check all of elements with condition.

const ratings = [3, 5, 4, 3, 5];
const goodOverallRating = ratings.every( rating => rating >= 3 );
// Result: goodOverallRating = true, because every element in array >= 3

 

2) Others

 

Like & Share if this topic is helpful for you 🙂

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s