Arrays with the help of ES6 now have uber cool methods! Let’s look at them with examples.
Array Static Methods
Array.from()
Converts arrayLike and iterator objects to arrays.
// ES5 way
var divs = document.querySelectorAll('div');
[].forEach.call(divs, function(node) {
console.log(node);
});
// ES6 way
var divs = document.querySelectorAll('div');
Array.from(divs).forEach(function(node) {
console.log(node);
});
// Also works with objects
Array.from({ 0: 'X', 1: 'Y', length: 2 })
// ['X', 'Y']
Array.of()
Creates a new Array instance with a variable number of arguments.
Array.of(0, true, undefined, null);
// [ 0, true, undefined, null ]
## Array.prototype Methods
### copyWithin()
javascript
[1, 3, 5, 7, 9].copyWithin(0, 3);
// [ 7, 9, 5, 7, 9 ]
[1, 3, 5, 7, 9].copyWithin(0, -2, -1);
// [ 7, 3, 5, 7, 9 ]
### fill()
javascript
[1,1,2,3,5,8].fill(4)
// [ 4, 4, 4, 4, 4, 4 ]
[1,1,2,3,5,8].fill(4, 1, 3)
// [ 1, 4, 4, 3, 5, 8 ]
### find() and findIndex()
javascript
const isEven = (element) => element % 2 === 0;
[1,2,3,5,7].find(isEven) // 2
[1,3,5,7,9].find(isEven) // undefined
[0,1,3,5,7].findIndex(isEven) // 0
[1,3,5,7].findIndex(isEven) // -1
### keys(), entries(), values()
javascript
const alphas = ['R', 'G', 'B'];
const keyIter = alphas.keys();
keyIter.next() // { value: 0, done: false }
const entrIter = alphas.entries();
entrIter.next().value // [0, 'R']
const valIter = alphas.values();
valIter.next().value // 'R'
#javascript#es6
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.