Javascript Array

The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.

Array.from

Creates a new, shallow-copied Array instance from an array-like or iterable object.

1
let squares = Array.from(document.querySelectorAll('.grid div'));

concat

Merge two arrays together.

1
2
3
4
var planets = ['Mars'];
var items = [ 'Pluto', 'Uranus', 'Saturn', 'Earth' ];
console.log(planets.concat(items));
// ["Mars", "Pluto", "Uranus", "Saturn", "Earth"]

every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

fill

1
2
3
this.state = {
squares: Array(9).fill(null),
};

forEach

The inbuilt forEach() method executes a provided function once for each array element.

1
2
3
4
5
let names = ['foo', 'bar'];

name.forEach(name => {
console.log('hello ' + name);
})

some

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

So for the below if any of the the functions functionA or functionB return true then the result is true.

1
itemArray.some(functionA, functionB);

slice

Call .slice() to create a copy of the squares array to modify instead of modifying the existing array.

1
2
3
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});

splice

Mutates an array by removing items/items in an array and replace them with new ones. Usage is itemArray.splice(startIndex, deleteCount, [NEW ARRAY ITEMS])

Example to delete items

1
2
3
var planets = ['Mars', 'Saturn', 'Pluto', 'Earth'];
console.log(planets.splice(2, 1)); // this will delete 'Pluto'
// ["Mars", "Saturn", "Earth"]

Example to add items

1
2
3
var planets = ['Mars', 'Saturn', 'Earth'];
console.log(planets.splice(1, 0, 'Pluto', 'Uranus')); // 1 for the first index, and 0 as we dont want to delete anything
// ["Mars", "Pluto", "Uranus", "Saturn", "Earth"]

Example to remove all after an index

1
2
3
4
5
var planets = ['Mars', 'Pluto', 'Uranus', 'Saturn', 'Earth'];
console.log(planets.splice(1));
// ["Pluto", "Uranus", "Saturn", "Earth"]
console.log(planets);
// ["Mars"]

length

The Array.prototype.length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

1
2
3
4
const arr = ['foo', 'bar', 'baz'];

console.log('arr.length = ' + arr.length);
// arr.length = 3