Friday, November 29, 2019

JavaScript Array Methods


returned value method
1 Array Iterator Methods
undefined array.forEach(function)
a new array array.map(function)
a new array array.filter(predicate)
element|undefined array.find(predicate)
index|-1 array.findIndex(predicate)
a boolean value array.every(predicate)
a boolean value array.some(predicate)
a value array.reduce(function[, initialValue])
a value array.reduceRight(function[, initialValue])
2 Stack and Queue Methods
the new length array.push(value1[, value2[, ...]])
the last element array.pop()
the new length array.unshift(value1[, value2[, ...]])
the first element array.shift()
3 Subarray Methods
a new array array.slice(startIndex[,endIndex])
a new array array.splice(startIndex, deleteCount[, value1[, value2[, ...]]])
the array itself array.fill(value, startIndex, endIndex)
the array itself array.copyWithin(target[, start[, end]])
4 Search Methods
index|-1 array.indexOf(searchValue[, fromIndex])
index|-1 array.lastIndexOf(searchValue[, fromIndex])
a boolean valuearray.include(searchValue)
5 Sort Methods
the array itself array.sort([function])
the array itself array.reverse()
6 Array to String Conversion Methods
a string array.join([separator])
a string array.toString()
a string array.toLocaleString()
Other Methods
a new array array.concat(value1[, value2[, ...]])

1 Array Iterator Methods

Features common to all array iterator methods are:

  • they accept a function as first argument and invoke that function for each element of the array
    array.method(function(elementi, i, array) [, ref]) { 
        /* function body */ 
    });
    
  • the first argument function is invoked with three arguments: the value of the element, the index of the element, the array itself.
  • they accept an optional second argument: if it is passed, the first argument function is invoked as a method of the second argument; that is the second argument assumes the value of this inside the first argument function
  • they do not modify the array on which they are called.
Array.prototype.forEach()
 array.forEach(function(array[i], i, array));
  • The forEach() method iterates through an array, invoking a function passed as argument for each array's element
  • The function argument is invoked with three arguments
  • If you want terminate iteration early you should throw an exception

Example

var data = [1,2,3,4,5];

// compute the sum of the elements
var result = 0;
data.forEach( value => result += value );
console.log(result); // 15
        
// square each array element
data.forEach( (value, i, array) => array[i] = value*value );
console.log(data); // [1, 4, 9, 16, 25] 
Array.prototype.map()
 result_array = array.map(function(array[i], i, array));
  • the map() method invokes the function you pass with every array element and returns a new array containing the values returned by these invocations.
  • the function passed as argument to map() is invoked in the same way as the function passed to forEach(), but for the map() method the function argument should return a value
  • if the array on which map() is invoked is sparse the returned array will be sparse
var data = [1,2,3,4,5];
var squared = data.map( x => x*x );
console.log(squared); // [1, 4, 9, 16, 25] 
Array.prototype.filter()
 sub_array = array.filter(predicate(x));
  • the filter() method returns a new array containing a subset of the elements of the array on which it is invoked
  • the function passed to filter() should be a predicate function (a function that returns true or false).
  • the predicate is invoked with every array's element, if the invocation returns true or a truthy value the element is added to the returned array.
  • the array returned by filter is always dense: filter() can be used to close gaps in a sparse array.

Example

var data = [0,1,2,3,4,5,6];
var evenValue = data.filter( x => x%2 == 0 );
console.log(evenValue); // [0, 2, 4, 6] 

// using filter() to close gaps in sparse arrays
var sparse = [0,1,,3,,5,,7];
var dense = sparse.filter( x => true );
console.log(dense); // [0, 1, 3, 5, 7]
Array.prototype.find() and Array.prototype.findIndex()
 element|undefined = array.find(predicate(x));
 index|-1 = array.findIndex(predicate(x));
  • the find() and findIndex() methods, takes a predicate function as first argument
  • they iterate through the array elements and stops as soon as an invocation to the predicate returns true
  • the find() method returns the array's element for which the predicate is true or undefined if no element is found
  • the findIndex() returns the element's index for which the predicate is true or -1 if no element is found

Example

let data = [1, 2, 3, 4, 5];

let index = data.findIndex( (x) => { return x%2 == 0; });
console.log(index); // 1, the first even value has index 1

let value = data.find( (x) => { return x%2 == 0; });
console.log(value); // 2, the first even value has value 2
Array.prototype.every() and Array.prototype.some()
 booleanValue = array.every(predicate(x));
 booleanValue = array.some(predicate(x));
  • the every() and some() methods apply a predicate function to the elements of an array and then return true or false
  • the every() method returns true if the argument function returns true for every element in the array, like the logic quantifier "for all" ∀
  • the some() method returns true if the argument function returns true for at least one element in the array, like the logic quantifier "there exist" ∃
data = [1,2,3,4,5];

var resultEvery = data.every( (x) => { return x%2 == 0; }) 
console.log(resultEvery); // false: not all values are even.

var resultSome = data.some( (x) => { return x%2 == 0; }) 
console.log(resultSome); // true: there is an even value.
5 Array.prototype.reduce() and Array.prototype.reduceRight()
value = array.reduce(function(x,y) [, initialValue]) {
    // reduce two values into one and return it
});

The reduce() method iterates through an array and uses a function to combine the array elements and produce a single value. This operation in functional programming is called reduction.

  • the reduce() method takes two arguments: the first argument is the function that performs the reduction. The second optional argument is a value to be passed as argument to the function at first invocation.
  • In fact, functions passed to with reduce() are invoked with four arguments: the first value is the result of the reduction so far, the following three parameters are the value of the array element, the index of the array element and the array. On the first call to the function, the first argument is the initial value you passed as the second argument to reduce(). On subsequent calls, it is the value returned by the previous invocation of the function.
    If you don't provide an argument as initial value, at first function invocation, the first and the second array elements will be passed to the function as argument.

Example

var array = [1,2,3,4,5];

// reduce five values into one by adding them - two at a time
var reduction = array.reduce(function(x,y) { return x+y; }, 0);
console.log(reduction); // 15

// reduce five values into one by multiplying them - two at a time
var factorial = array.reduce(function(x,y) { return x*y; }, 1);
console.log(factorial); // 120
 value = array.reduceRight(function(x,y)[, initialValue]);
  • the reduceRight() method works like reduce(), except that it processes array elements from highest index to lowest, from right to left.

using reduce() with objects

reduce() and reduceRight() are not meant only to work with array of numbers. Consider the union() function, this function expects two objects and returns another object that has the properties of both, so it works as a reduction function. We can use reduce(union) to compute the union of an array of objects

/*
 * Copy the enumerable properties of two objects into a new object and return it
 */
function union(p, o) {
    var un = {};
    for(key in p) 
        un[key] = p[key];
    for(key in o) 
        un[key] = o[key];
    return un;
}

var objects = [{eyeColor:"green"}, {hairColor:"brown"}, {race:"Caucasian"}];
var merged = objects.reduce(union);
console.log(merged); // Object {eyeColor: "green", hairColor: "brown", race: "Caucasian"}

Example: applying the forEach(), map() and reduce() methods

var cart = [
    {
        title: "JavaScript: The Definitive Guide",
        author: "David Flanagan",
        price: 39 
    },
    {
        title: "Professional JavaScript for Web Developers",
        author: "Nicholas C. Zakas",
        price: 32
    },
    {
        title: "JavaScript and Jquery, Interactive Front-End Web Development",
        author: "Jon Duckett",
        price: 29
    }
];

let total=0;

// iterate the cart array to sum price into total
cart.forEach(elem => total += elem.price);
console.log(total); // 100

// get an array of price values and sum the values
total = cart.map(elem => elem.price).reduce((x,y) => x+y);
console.log(total); // 100

2 Stack and Queue Methods

Array.prototype.push() and Array.prototype.pop()
length = array.push(value1[, value2[, ...]])
last_element = array.pop()
  • the push() method adds one or more elements to the end of an array and returns the new length of the array.
  • the pop() method removes the last element from an array and returns that element.
  • they both modify the array in-place.
var array = [];
console.log(array.push(1,2,"three")); // 3 - the new length
console.log(array); // [1,2,"three"]
console.log(array.pop()); // "three" - the removed element
console.log(array); // [1,2]    
console.log(array.push(3)); // 3 - the new length
console.log(array); // [1, 2, 3] 

// spread the element of the array
array.push(...[4,5,6])
console.log(array); // [1, 2, 3, 4, 5, 6] 
Array.prototype.unshift() and Array.prototype.shift()
length = array.unshift(value1[, value2[, ...]])
first_element = array.shift()
  • The unshift() method adds one or more elements to the beginning of the array and returns the new length of the array. It shifts all existing array's elements to right by increasing their indexes.
  • The shift() method removes the first element from an array and returns that element. It shifts all existing array's elements to left by decreasing their indexes.
var array = [];
console.log(array.unshift("one")); // 1 - the new length
console.log(array.unshift("two")); // 2 - the new length
console.log(array.unshift("three")); // 3 - the new length
console.log(array); // ["three", "two", "one"]
console.log(array.shift()); // "three" 

Note:

  • the unshift() and shift() methods insert and remove elements from the beginning of an array, whereas push() and pop() insert and remove elements from the end of an array.
  • a stack is known as a Last-In-First-Out (LIFO) structure, meaning that the most recently added item is the first one removed. To handle a JavaScript array as a stack you can use the pair of methods push() and pop() or the pair of methods unshift() and shift(). Using push() and pop() methods is more efficient than using unshift() and shift(), because the other elements must not be shifted
  • a queue adds items to the end of a list and retrieves items from the front of a list. A queue is known as First-In-First-Out (FIFO) data structure. Using shift() and push() methods allows arrays to be used as queues.

3 Subarray Methods

Array.prototype.slice()
 sub_array = slice(begin[,end]);

the slice() method creates a new array that is a subarray of the specified array.

  • it doesn't modify the original array
  • it returns the new subarray
  • the begin parameter specifies the index from which to start extracting elements
  • the end parameter specifies the index at which to stop extracting elements, the end element is not incuded. When end is omitted, this means to extract until array.length
  • a negative index as argument means to start counting from the end of the array.
var arr = ["one", "two", "three", "four", "five", "six"];
    
var new_array = arr.slice(0,3); // begin is 0, end is 3
console.log(new_array); // ["one", "two", "three"]
    
new_array = arr.slice(3); // if end is omitted it means the last element
console.log(new_array); // ["four", "five", "six"] 
    
new_array = arr.slice(1,-1); // begin is 1, end is the last element
console.log(new_array); // ["two", "three", "four", "five"]
    
new_array = arr.slice(-2,-1); // begin is the second-last, end is the last
console.log(new_array); // ["five"]
Array.prototype.splice()
deletedElementsArray = array.splice(start, deleteCount[, item1[, item2[, ...]]])

The splice() method can remove elements from an array, add elements into an array or do both actions at a time.

  • it modifies the array in-place
  • it returns the array of the deleted elements.
  • the start parameter indicates the index, included, where to start removing/inserting elements
  • the deleteCount parameter indicates the number of array elements to be removed. When this parameter is omitted, this means all elements from start index through the end of the array are to be deleted.
  • the item1, item2, ... parameters are the elements to be added to the array. If omitted splice will only remove elements.

Examples:

// remove all elements starting from index 4
var array = ["one", "two", "three", "four", "five", "six"];
var deleted = array.splice(4); 
console.log(deleted); // ["five", "six"]
console.log(array); // ["one", "two", "three", "four"]

// remove two elements and insert two elements
var array = ["one", "two", "three", "four", "five", "six"];
var deleted = array.splice(2, 2, "3", "4"); 
console.log(deleted); // ["three", "four"]
console.log(array); // ["one", "two", "3", "4", "five", "six"] 

// search given element and if found remove it
let fruits = ["apple", "banana", "cherry", "orange", "pasta", "kiwi"];
fruits.splice(fruits.indexOf("pasta"),1); 
fruits // -> ["apple", "banana", "cherry", "orange", "kiwi"]
Array.prototype.fill()
 modifiedArray = array.fill(value, startIndex, endIndex)

The fill() method change the value of the elements of an array to the specified value

  • it modifies the array it is called on
  • it returns the modified array
  • the startIndex optional second parameter specifies the index where to start setting the value, when omitted it is implied the index value 0
  • the endIndex optional third parameter specifies the index, not included, where to end setting the value. If the value is negative, it is relative to the end of the array
var array = new Array(3);
var result = array.fill("zero"); 
console.log(result); // ["zero", "zero", "zero"]
result = array.fill("one", 1);
console.log(result); // ["zero", "one", "one"]
result = array.fill("two", 2);
console.log(result); // ["zero", "one", "two"]
Array.prototype.copyWithin()
 modifiedArray = array.copyWithin(target[, start[, end]])

The copyWithin() method copies a slice of the elements of an array to another place in the same array, without modifying the array length

  • it modifies the array it is called on
  • it returns the modified array
  • the first argument specifies the index where to move the element
  • the second optional argument specifies the index of the first element to be moved, if omitted it is implied the index value of 0
  • the third optional argument specifies the index of the last element, not included, to be moved. If omitted it is implied the length value of the array
  • note: the copyWithin() method is meant for typed array
let array = [1, 2, 3, 4, 5];
array.copyWithin(1); // target is 1, start is 0; copy all the elements to index 1    
console.log(array); // [1, 1, 2, 3, 4] (every element is shifted to the right by one)

let array2 = [1, 2, 3, 4, 5];
array2.copyWithin(0,1); // target is 0, start is 1 
console.log(array2); // [2, 3, 4, 5, 5] (every element is shifted to the left by one)

let array3 = [1, 2, 3, 4, 5];
array3.copyWithin(3); // target is 3, copy all the elements to the index 3
console.log(array3); // [1, 2, 3, 1, 2]

let array4 = [1, 2, 3, 4, 5];
array4.copyWithin(0, 3); // target is 0, start is 3; copy the elements with index 3 and 4 to index 0
console.log(array4); // [4, 5, 3, 4, 5] 

Arrays' methods indexOf(), lastIndexOf() and includes() are similar to the Strings' methods with same names.

Array.prototype.indexOf() and Array.prototype.lastIndexOf()
 index = array.indexOf(searchValue[, fromIndex]);
 index = array.lastIndexOf(searchValue[, fromIndex]);
  • indexOf() and lastIndexOf() methods search for the specified value in array's elements
  • They return the index of the found element or -1 if the value is not present
  • indexOf() start the search from the beginning and lastIndexOf() from the end of the array
  • indexOf() and lastIndexOf() methods take a second optional argument that specify the array index where to start search
array = [1,2,3,1,2,3,1,2,3];
    
var position = array.indexOf(1);
console.log(position); // 0
    
position = array.lastIndexOf(1);
console.log(position); // 6
    
console.log(array.indexOf(4)); // -1: no element with value 4
Array.prototype.includes()

The includes() method determines whether an array contains a specified value amongst its elements

  • it takes a single argument, that is the value to be searched
  • it returns true, if the passed argument is found
  • it uses a different algorithm to check equality than the indexOf method. This algorithm consider NaN to be equal to itself
array = [1, 2, 3, NaN];
    
console.log(array.includes(1)); // true
console.log(array.includes(4)); // false
console.log(array.includes(NaN)); // true

5 Sort Methods

Array.prototype.sort()
 array.sort([function])

the sort() method sorts an array elements in alphabetical order

  • it modifies the array in-place and returns the modified array
  • you can sort into some order other than alphabetical by passing a comparison function as an argument to sort()
// sort numbers in alphabetical order
let arrayOfNumbers = [0, 1, 11, 111, 2, 22, 222];
arrayOfNumbers.sort();
console.log(arrayOfNumbers); // [0, 1, 11, 111, 2, 22, 222]

// sort words in alphabetical order
let arrayOfWords = ["Zimbabwe", "Denmark", "canada", "America"];
arrayOfWords.sort();
console.log(arrayOfWords); // ["America", "Denmark", "Zimbabwe", "canada"]

You can sort in other orders by passing a comparison function as an argument to sort().

// sort numbers in numerical order
let arrayOfNumbers = [0, 1, 11, 111, 2, 22, 222];
arrayOfNumbers.sort( (n1, n2) => { return n1-n2 } );
console.log(arrayOfNumbers); // [0, 1, 11, 111, 2, 22, 222]
  
// sort words in case-insensitive alphabetical order
var arrayOfWords = ["Zimbabwe", "Denmark", "canada", "America"];
arrayOfWords.sort( (word1, word2) => {
  let uppercase1 = word1.toUpperCase();
  let uppercase2 = word2.toUpperCase();
  if (uppercase1 < uppercase2) return -1;
  if (uppercase1 > uppercase2) return +1;
  return 0;
});
console.log(arrayOfWords); // ["America", "canada", "Denmark", "Zimbabwe"]
Array.prototype.reverse()
 array.reverse()

The reverse() method reverses the order of the elements of an array.

  • it modifies the array in-place and returns the modified array
let array = ["one", "two", "three"];
array.reverse(); // elements order is reversed
console.log(array); // ["three", "two", "one"]

6 Array to String Conversion Methods

The array class defines three methods that convert an array to string: join(), toString() and toLocaleString()

  • you may use one of the above mentioned methods, when creating messages for log and errors
  • you should NOT use one of the above mentioned methods, if you want to save the content of an array for reusing it later:
    • serialize the array with JSON.stringify() instead.
Array.prototype.join()
var array = ["one", "two", "three"];

console.log(array.join());    //  'one,two,three'
console.log(array.join("-")); //  'one-two-three'
console.log(array.join(" ")); //  'one two three'

The join() method concatenates all the elements of an array into a string and returns the result string

  • when concatenating array elements, it uses a default comma to separate elements
  • it takes an optional argument, to be used as element separator in the result string
  • note: the array.join() method is the inverse of the string.split() method, which breaks a string creating an array
Array.prototype.toString()
 string = array.toString()

The toString() method works like the join() method

  • it converts each element to a string and join them using a comma as element separator
  • it overrides the toString() method of Object class
console.log([1,2,3].toString()); // '1,2,3'
console.log(["a", "b", "c"].toString()); // 'a,b,c'
console.log([1, [2,'c']].toString()); // '1,2,c'

console.log(["a", "b", "c"].toLocaleString()); // 'a,b,c'
Array.prototype.toLocaleString()

The toLocaleString() method is the locale version of the toString() method

  • it converts each array element to a string by calling the toLocaleString() method of the element and then it concatenates the resulting strings using a locale-specific separator string
Array.prototype.concat()
 newArray = array.concat(value1[, value2[, ...]]);

The concat() method creates a new array containing the elements of the array on which is called and the values provided as arguments

  • it returns the new array
  • it does not modifies the array it is called on
var array = ["one", "two", "three"];
var new_array = array.concat("4", "5");
console.log(new_array); // ["one", "two", "three", "4", "5"]     

If the argument to concat() is an array, its elements are concatenated to the array, not the array.

var array = ["one", "two", "three"];
var new_array = array.concat(["4", "5"],["6", "7"]);    
console.log(new_array); // ["one", "two", "three", "4", "5", "6", "7"]

7 Invoking Arrays Methods on Strings

In ECMAScript 5, strings behave like arrays, so you can invoke array methods on strings.

Example: brackets operator as alternative to charAt() method

let string = "this is a string";
console.log(string.charAt(0)); //  "t"
console.log(string[0]); //  "t"

If you want to invoke the array methods on strings you have to make an indirect invocation by the Function.call() method.

Example: invoking the join() and filter() methods on a string

const string = "Hello World";

// join the characters of the string
const joined = Array.prototype.join.call(string, " ")       
console.log(joined); // "H e l l o   W o r l d"

// filter the characters of the string
const filteredAndJoined = Array.prototype.filter.call(string, function(x) {
  return x.match(/[^aeiou]/);
}).join("");                        
console.log(filteredAndJoined); // "Hll Wrld" 

Array methods that modify arrays in-place, like reverse(), splice(), etc, do not work on strings because strings are immutable. So you can convert the string into an array and then use these methods which modify array.

Example: invoking the reverse() method on a string

let string = "Hello JS"; // start from a string     
let array = string.split(""); // convert it to array 
let reversedString = array.reverse().join(""); // apply the reverse array method
console.log(reversedString);  // -> "SJ olleH"

No comments:

Post a Comment