JavaScript - Arrays

javascript

http://blog.duruk.net/2011/06/19/nodelists-and-arrays-in-javascript/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/iterable
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
http://web.mit.edu/jwalden/www/isArray.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Basic
concat
fill
filter
find
findIndex
indexOf
includes
lastIndexOf
join
forEach
Array.observe - deprecated
Array.from
Array.of
entries
keys
every
map
reduce
reduceRight

// There are 3 ways to create array in JavaScript:
1. By array literal
2. By creating instance of Array
3. By using an Array constructor

var x = ['a', 'b', 'c'];
var x = new Array('a', 'b', 'c');
var x = new Array(7); // Avoid.  This is ambiguous

// To use Math.max to find the maximum value in an array:
Math.max.apply(null, arr); 

Calling an array object’s reverse() method doesn’t only return the array in 
reverse order, it also reverses the order of the array itself.  The reverse() 
method returns a reference to the array itself (i.e., in this case, arr1). 
As a result, arr2 is simply a reference to (rather than a copy of) arr1. 
Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), 
arr1 will be affected as well since arr1 and arr2 are simply references to the 
same object.

Passing an array to the push() method of another array pushes that entire array 
as a single element onto the end of the array. As a result, the statement 
arr2.push(arr3); adds arr3 in its entirety as a single element to the end of 
arr2 (i.e., it does not concatenate the two arrays, that’s what the concat() 
method is for).

Like Python, JavaScript honors negative subscripts in calls to array methods 
like slice() as a way of referencing elements at the end of the array; e.g., a 
subscript of -1 indicates the last element in the array, and so on.

// Array.prototype.reverse()
The reverse() method reverses an array in place. The first array element becomes 
the last, and the last array element becomes the first.

a.reverse()

The reverse method returns the reversed array.

The reverse method transposes the elements of the calling array object in place, 
mutating the array, and returning a reference to the array.

var a = ['one', 'two', 'three'];
var reversed = a.reverse(); 
console.log(a);        // ['three', 'two', 'one']
console.log(reversed); // ['three', 'two', 'one']

// Array.prototype.shift()
The shift() method removes the first element from an array and returns that 
element. This method changes the length of the array.

arr.shift()

The shift method returns the element that was removed.

The shift method removes the element at the zeroeth index and shifts the values 
at consecutive indexes down, then returns the removed value. If the length 
property is 0, undefined is returned.

var a = [1, 2, 3];
a.shift();
console.log(a); // [2, 3]

// Array.prototype.slice()

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.

arr.slice()
arr.slice(begin)
arr.slice(begin, end)

begin: Optional.  Zero-based index at which to begin extraction.  As a negative 
  index, begin indicates an offset from the end of the sequence. slice(-2) 
  extracts the last two elements in the sequence.  If begin is undefined, slice 
  begins from index 0.
end: Optional.  Zero-based index at which to end extraction. slice extracts up 
  to but not including end.  slice(1,4) extracts the second element through the 
  fourth element (elements indexed 1, 2, and 3).  As a negative index, end 
  indicates an offset from the end of the sequence. slice(2,-1) extracts the 
  third element through the second-to-last element in the sequence.  If end is 
  omitted, slice extracts through the end of the sequence (arr.length).

The slice method returns a new array containing the extracted elements.

The slice method does not alter the original array. It returns a shallow copy 
of elements from the original array. Elements of the original array are copied 
into the returned array as follows:

1. For object references (and not the actual object), slice copies object 
   references into the new array. Both the original and new array refer to the 
   same object. If a referenced object changes, the changes are visible to both 
   the new and original arrays.
2. For strings, numbers and booleans (not String, Number and Boolean objects), 
   slice copies the values into the new array. Changes to the string, number or 
   boolean in one array does not affect the other array.

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

// Array.prototype.some():
The some() method tests whether some element in the array passes the test 
implemented by the provided function.

arr.some(callback[, thisArg])

callback: Function to test for each element, taking three arguments: 
1. currentValue: The current element being processed in the array.
2. index: The index of the current element being processed in the array.
3. array: The array some() was called upon.

thisArg: Optional. Value to use as this when executing callback.

The some() method returns true if the callback function returns a truthy value 
for any array element; otherwise, false.

The some() method does not mutate the array on which it is called.

function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

[2, 5, 8, 1, 4].some(elem => elem > 10);  // false
[12, 5, 8, 1, 4].some(elem => elem > 10); // true

var fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
  return arr.some(arrVal => val === arrVal);
}
checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true

// Array.prototype.sort():
The sort() method sorts the elements of an array in place and returns the array. 
The sort is not necessarily stable. The default sort order is according to 
string Unicode code points.

arr.sort()
arr.sort(compareFunction)

compareFunction: Optional.  Specifies a function that defines the sort order. 
  If omitted, the array is sorted according to each character's Unicode code 
  point value, according to the string conversion of each element.

If compareFunction is not supplied, elements are sorted by converting them to 
strings and comparing strings in Unicode code point order. For example, 
"Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but 
because numbers are converted to strings, "80" comes before "9" in Unicode order.

If compareFunction is supplied, the array elements are sorted according to the 
return value of the compare function. If a and b are two elements being compared, 
then:

1. If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. 
   a comes first.
2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to 
   each other, but sorted with respect to all different elements. Note: the 
   ECMAscript standard does not guarantee this behaviour, and thus not all 
   browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
3. If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
4. compareFunction(a, b) must always return the same value when given a specific 
   pair of elements a and b as its two arguments. If inconsistent results are 
   returned then the sort order is undefined.

The compare function has the following form:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

To compare numbers instead of strings, the compare function can simply subtract 
b from a. The following function will sort the array ascending (if it doesn't 
contain Infinity and NaN):

function compareNumbers(a, b) {
  return a - b;
}

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  // a must be equal to b
  return 0;
});
// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

For sorting strings with non-ASCII characters, i.e. strings with accented 
characters (e, é, è, a, ä, etc.), strings from languages other than English: 
use String.localeCompare. This function can compare those characters so they 
appear in the right order.

var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
  return a.localeCompare(b);
});
// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']

The compareFunction can be invoked multiple times per element within the array. 
Depending on the compareFunction's nature, this may yield a high overhead. The 
more work a compareFunction does and the more elements there are to sort, the 
wiser it may be to consider using a map for sorting. The idea is to walk the 
array once to extract the actual values used for sorting into a temporary array, 
sort the temporary array and then walk the temporary array to achieve the right 
order.

// the array to be sorted
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
  return { index: i, value: el.toLowerCase() };
})
// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
  return +(a.value > b.value) || +(a.value === b.value) - 1;
});
// container for the resulting order
var result = mapped.map(function(el){
  return list[el.index];
});

// Array.prototype.splice()
The splice() method changes the content of an array by removing existing 
elements and/or adding new elements.

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

start: Index at which to start changing the array (with origin 0). If greater 
  than the length of the array, actual starting index will be set to the length 
  of the array. If negative, will begin that many elements from the end of the 
  array.
deleteCount: Optional.  An integer indicating the number of old array elements 
  to remove. If deleteCount is 0, no elements are removed. In this case, you 
  should specify at least one new element. If deleteCount is greater than the 
  number of elements left in the array starting at start, then all of the 
  elements through the end of the array will be deleted.  If deleteCount is 
  omitted, deleteCount will be equal to (arr.length - start).

The splice method returns an array containing the deleted elements. If only one 
element is removed, an array of one element is returned. If no elements are 
removed, an empty array is returned.

If you specify a different number of elements to insert than the number you're 
removing, the array will have a different length at the end of the call.

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(2, 0, "drum"); 
// myFish is ["angel", "clown", "drum", "mandarin", "surgeon"]

//Remove 0 elements from index 2, and insert "drum"
var myFish = ["angel", "clown", "mandarin", "surgeon"];
var removed = myFish.splice(2, 0, "drum");

//Remove 1 element from index 3:
var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"];
var removed = myFish.splice(3, 1);

// Array.prototype.toLocaleString():
The toLocaleString() method returns a string representing the elements of the 
array. The elements are converted to Strings using their toLocaleString methods 
and these Strings are separated by a locale-specific String (such as a comma “,”).

arr.toLocaleString();

The toLocaleString() method of the Array class returns a string representing 
the elements of the array.

// Array.prototype.toString():
The toString() method returns a string representing the specified array and 
its elements.

arr.toString()

The toString method of an Array object returns a string representing the 
elements of the array.

The Array object overrides the toString method of Object. For Array objects, 
the toString method joins the array and returns one string containing each array 
element separated by commas.

JavaScript calls the toString method automatically when an array is to be 
represented as a text value or when an array is referred to in a string 
concatenation.

Starting in JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th 
edition semantics, the toString() method is generic and can be used with any 
object. Object.prototype.toString() will be called, and the resulting value 
will be returned.

var months = ["Jan", "Feb", "Mar", "Apr"];
months.toString(); // "Jan,Feb,Mar,Apr"

// Array.prototype.unshift()
The unshift() method adds one or more elements to the beginning of an array and 
returns the new length of the array.

arr.unshift([element1[, ...[, elementN]]])

The unshift method returns the new length property of the object upon which the 
method was called.

var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a); // [4, 5, 1, 2, 3]

//Array.prototype.values():
The values() method returns a new Array Iterator object that contains the values 
for each index in the array.

arr.values()

The values() method returns a new Array iterator object.

var a = ['w', 'y', 'k', 'o', 'p']; 
var iterator = a.values();
console.log(iterator.next().value); // w 

// Iteration using for...of loop
var arr = ['w', 'y', 'k', 'o', 'p'];
var iterator = arr.values();
for (let letter of iterator) {
  console.log(letter);
}

// Array.prototype[@@iterator]():
The initial value of the @@iterator property is the same function object as the 
initial value of the values() property.

arr[Symbol.iterator]()

//Iteration using for...of loop:
var arr = ['w', 'y', 'k', 'o', 'p'];
var eArr = arr[Symbol.iterator]();
// your browser must support for..of loop
// and let-scoped variables in for loops
for (let letter of eArr) {
  console.log(letter);
}

How can we create a literal array?

var a = ["dog", "cat", "hen"];

var a = new Array();
a[0] = "dog";
a[1] = "cat";
a[2] = "hen";

var movies = new Array( 'Transformers', 'Avatar', 'Indiana Jones');
var movies = ['Transformers', 'Avatar', 'Indiana Jones'];

How can we join elements of an array into a string separated by a separator?

var arr = [];
var str = arr.join(',');

How can we join two arrays to create a new array?

var arr1 = [];
var arr2 = [];
var arr3 = [];

var arr1 = arr1.concat(arr2, arr3);

The concat method can take multiple arrays as parameters. It returns a new array and does not change the existing array (the one that is used to invoke the concat method).

How can we find the largest number in an array?

var numbers = [3, 342, 23, 22, 124];
numbers.sort(function(a,b) {return b - a}); // need to verify if the sort function directly modify the numbers array
var result = numbers[0];
var result = Math.max(12, 123, 3,2, 433, 4);

How can we delete an element from an array?

Use the delete function:

delete myArray[5];

How can we sort an array?

var numbers = [3, 342, 23, 22, 124];
numbers.sort(comparisonFunction);

The comparison function should take p1 and p2, returns negative if p1 < p2, zero if equal, and positive if p1 > p2.

What are some of the ways to empty an array?

this.options.length = 0;
this.options = new Array();

Are arrays considered as objects in JavaScript?

Objects in JavaScript are mutable key collections. In JavaScript, arrays are objects.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License