Press "Enter" to skip to content

List some handy functions in Javascript

Array.isArray()

The isArray() method checks if the specified parameter is an array. Returns a true if is an array.

Array.isArray('string'); // false
Array.isArray(123); // false
Array.isArray(['I am Array']); // true
Array.isArray({key: value}); // false

Array.find()

The find() method is used to get the value of the first element in the array that satisfies the provided condition.

array.find(function(currentValue, index, arr),thisValue)
['apple','bannna','pear'].find(function(name) {
    return name === 'apple';
});

// or ES6 arrow functions
['apple','bannna','pear'].find(name => name === 'apple');

const people = [
  { name: 'Tom', username: 'tom2020' },
  { name: 'Jason', username: 'jason009' },
  { name: 'Rose', username: 'rose123' },
];
people.find(person => person.name === 'Tom');
// output: { name: 'Tom', username: 'tom2020' }

// find array item with index of 3
const atIndex = items.find(function(element, index){
  return index === 3
})

// display array item found
console.log(atIndex)

Array.filter()

The filter() method returns an array containing elements of the target array that match the set test. The callback function containing a test is passed as an argument to the filter method.

const filteredArray = targetArray.filter(callbackFunction(element[,index[,array]])[, thisArg])
const names = ['Kevin', 'Peter', 'Jason', 'Epso', 'Hang'];

// Filter the array for names having 'o'
const nameHasO = names.filter(name => name.includes('o'));

Another good example: Boolean() is also a function that returnstrue when true,

or false when if the value is omitted or is 0-0nullfalseNaNundefined, or the empty string ("").

var array = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];

var newArray = array.filter(Boolean);  // [1, 2, "b", {}, 3, 5]; 

Array.every()

The every method checks that each element in an array passes a set test. This method will return true if all the elements pass the test. Otherwise returns false.

array.every(callback(element[, index[, array]])[, thisArg])
const students = [{name: 'Tom', score: 70} , {name: 'Jason', score: 80}, {name: 'King', score: 95}];

// Test callback function
const studentsPassed = students.every(student => student.score >= 60);

console.log(studentsPassed) // Output: true

Array.some()

This method checks if any of the elements contained in an array passes a set test. If at least one of the elements passes this test, true is returned. This method only returns a Boolean.

const bool = array.some(callback(element[, index[, array]])[, thisArg])
const cities = [{city: 'Oakland', zipCode: '94602'}, {city: 'San Francisco'}];

// Verify properties of an object
let hasZipCode = cities.some(function(city){
  return !!city.zipCode;
})
console.log(hasZipCode); // Output: true

Array.toString() 

This method returns a String representation of the elements within the calling array. This method is somewhat similar to the join(',') method.

['Hello', 'World!'].toString()
// 'Hello,World!'
['1', '2', '3', '4'].toString()
// '1,2,3,4'

Array slice() vs. splice() vs. split()

According to the documentation: The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

let array = [1,2,3,4,5]
console.log(array.slice(2));
// output: [3, 4, 5], returned selected element(s).
 
console.log(array.slice(-2));
// output: [4, 5], returned selected element(s).
console.log(array);
// output: [1, 2, 3, 4, 5], original array remains intact.
 
           -5 -4 -3 -2 -1
            |  |  |  |  |
let array2=[6, 7, 8, 9, 10];
             |  |  |  |  |
             0  1  2  3  4
console.log(array2.slice(2,4));
// output: [8, 9]
 
console.log(array2.slice(-2,4));
// output: [9]
 
console.log(array2.slice(-3,-1));
// output [8, 9]

The splice() method changes an existing array by removing, adding and/or replacing specified elements from it. The method mutates the original array and returns an array of all elements removed from the array. An empty array is returned if no elements are removed.

  • The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
  • The splice() method changes the original array and slice() method doesn’t change the original array.
  • The splice() method can take n number of arguments:
let array = [1,2,3,4,5];
console.log(array.splice(2));
// output: [3, 4, 5], returned removed item(s) as a new array object.
 
console.log(array);
// output: [1, 2], original array altered.
 
var array2 = [6,7,8,9,10];
console.log(array2.splice(2,1));
// output: [8]
 
console.log(array2.splice(2,0));
// output: [] , no item(s) selected means no item(s) removed.
 
console.log(array2);
// output: [6,7,9,10]
 
let array3 = [11,12,13,14,15];
console.log(array3.splice(2,1,"apple","banana"));
// output: [13]
 
console.log(array3);
// output: [11, 12, "apple", "banana", 14, 15]
 
           -5 -4 -3 -2 -1
            |  |  |  |  |
var array4=[16,17,18,19,20];
             |  |  |  |  |
             0  1  2  3  4
 
console.log(array4.splice(-2,1,"string"));
// output:  [19]
 
console.log(array4);
// output: [16, 17, 18, "string", 20]

Split ( )

Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array. Syntax:

string.split(separator, limit);

  • Separator: Defines how to split a string… by a comma, character etc.
  • Limit: Limits the number of splits with a given number
let str = "How are you doing today?";
let newStr = str.split(" ", 3);
// newStr: ['How','are','you']

This page will be updated every time if I find something interesting.