[JavaScript – ES2015] Arrays

Array is a main collection object in JavaScript. ES2015 enhanced the Array functionalities.

 

1. Arrays – find(), findIndex()

By providing the predicate function, you can find the first matching element or the 0-based index of it in an array.

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

console.log(numbers.find(n => n === 3)); // 3
console.log(numbers.find(n => n > 3)); // 4

console.log(numbers.findIndex(n => n >= 2)); // 1
console.log(numbers.findIndex(n => n === 5)); // 4

 

2. Arrays – fill()

The fill(value, startIndex, endIndex) fills the section with the value. Note that it replaces the value from (startIndex ~ endIndex-1); it does not insert values.

let numbers = [0, 0, 0, 0, 0];
numbers.fill(1, 2);
console.log(numbers.join()); // 0,0,1,1,1

numbers = [0, 0, 0, 0, 0];
numbers.fill(1, 2, 3);
console.log(numbers.join()); // 0,0,1,0,0

numbers = [0, 0, 0, 0, 0];
numbers.fill(1, 2, 4);
console.log(numbers.join()); // 0,0,1,1,0

 

3. Arrays – Array.of(), Array.from()

Array.of() is similar to new Array(…), but without special one-argument behavior. With one argument, new Array() creates an array with the length of specified number, not a single value array. Array.of() fixes this issue.

let numbers = new Array(5);  
console.log(numbers.join()); // ,,,,
console.log(numbers.length); // 5

numbers = Array.of(5);
console.log(numbers.join()); // 5
console.log(numbers.length); // 1

numbers = new Array(1, 2, 3);
console.log(numbers.join()); // 1,2,3

numbers = Array.of(1, 2, 3);
console.log(numbers.join()); // 1,2,3

Another JavaScript design error is the array-like object. The “document.querySelectorAll()” returns a collection object but not an array object. This is a design error but we are stuck with it. The fix in ES2015 is the “Array.from()” method.

let elements = document.querySelectorAll('*');  
console.log(typeof elements.fill); // undefined.

let arrayElements = Array.from(elements);
console.log(typeof arrayElements.fill); // function

 

4. Arrays – Iterators

Iterator and the “for…of” loop are the big feature enhancements that are included in ES2015. Arrays can have 3 iterators.

  • entries() -> [index, value]
  • keys() -> index
  • values() -> value
let numbers = [10, 20, 30];  

let entries = numbers.entries();
let keys = numbers.keys();
let values = numbers.values();

for (let entry of entries) {
  console.log(entry); // [0, 10], [1, 20], [2, 30]
}
for (let key of keys) {
  console.log(key); // 0,1,2
}
for (let value of values) {
  console.log(value); // 10,20,30
}

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