In this post we are going to learn about the 9 Useful array methods in ES6that includes array.of(), array.from(), array.index(), array.findindex(), array.fill(), array.copywithin() and many more with the help of examples.
ES6 Array Methods
- Array.of()
- Array.from()
- Array.find()
- Array.findIndex()
- Array.fill()
- Array.copyWithin()
- Array.entries()
- Array.keys()
- Array.values()
Problem with Array constructor in ES5
In ES5, passing a single numeric value to the array constructor creates an empty array whose size is equal to the number.
As we can see, In the below code, we are creating a myarray bypassing numeric value 5 to the array constructor. It created an empty array of length 5. whereas accessing value at index 0 return undefined.
let myarray = new Array(5);
console.log('array length =',myarray.length);
console.log('accessing value at first index =',myarray[0]);
Output
array length = 5
accessing value at first index = undefined
Note: This behavior is different when we pass a non-numeric value to the array constructor. It creates a non-empty array with a passed value. This is the strange and error-prone behavior of the array constructor.
let myarray = new Array('5');
console.log('array length =',myarray.length);
console.log('accessing value at first index =',myarray[0]);
Output
array length = 1
accessing value at first index = 5
1. ES6 Array.of()
In ES6 Array.of() method is introduced to overcome this problem.Array.of() is similar to Array constructor except it creates a new array instance from a variable or number of arguments, no matter number or type of arguments.
Syntax
Array.of(element0 [, element1[, ...[, elementN]]])
Parameters
- Parameters: element0 …..elements are elements that are used to create an array.
- Return Value: It returns a new array instance.
Example
let myarray = Array.of(5);
console.log('array length =',myarray.length);
console.log('accessing value at first index =',myarray[0]);
Output
array length = 1
accessing value at first index = 5
2.Array.from() in ES6
Array. from the () method is introduced in ES6, It is used to create an array from an array-like or iterate object (Set,Map).
Syntax
Array.from(targetobj, mapFn , thisArg]])
Parameters
- targetobj : It is array-like or iterable object to convert to an array.
- mapfn: It is optional Map function parameter and to call on every element of the array.
- thisArg: It is also optional to use as this when executing the mapFn.
Let us understand this with example.here, we are creating a new array from a iterable object Set
const device = new Set(['laptop', 'tv', 'mobile', 'tablet']);
let devicearray = Array.from(device)
console.log(devicearray)
Output
[ 'laptop', 'tv', 'mobile', 'tablet' ]
In ES5, To create an array from an array-like object. We had two ways.
- Iterate over array elements
- array.slice()
1. Iterate over array elements
In ES5, to create an array from the array-like object we had to loop over all the elements of the array and need to add each element in a new array while iterating the loop. Let us understand this with an example:
function createnewarray() {
var newarray = [];
for (var index = 0; index < arguments.length; index++) {
newarray.push(arguments[index]);
}
return newarray;
}
var samplearray = createnewarray(1, 2, 'Greet');
console.log(samplearray);
var samplearr = Array.from([1,2,'Greet'])
console.log('Using array.from() :',samplearr);
Output
[ 1, 2, 'Greet' ]
Using array.from() : [ 1, 2, 'Greet' ]
Using Slice()
Another simple way to achieve the same is slice() method of the Array.prototype()
function createnewarray() {
return Array.prototype.slice.call(arguments);
}
var samplearray = createnewarray(1, 2, 'Greet');
console.log(samplearray);
Output
[ 1, 2, 'Greet' ]
3. Array.find()
In ES6, find() is a new method added to the array. prototype, we use it to find the value from the array that satisfies the given condition, we pass the condition to the find() method using an arrow function, the condition executes against every element of the array. As soon as it finds a value that satisfies the given condition that value is returned. It does not check all the value that satisfies the condition that is why we get only one value as output.
Syntax
array.find(callback(element, index, array)[, thisArg])
Parameters
- Callback: This is a function to execute on each element of the array. The callback function takes these three-arguments.
- Element: it represents the current element.
- index: It represents the index of the current element.
- Array: It represents the array on we are calling the find() method.
- thisarg: It is an optional parameter. It is a value that is used as this while using callback.
Return value:
The callback function in the find() method executes for each element of the array, until the callback returns true, after getting the true find() method returns the value of that element. Otherwise, it returns undefined.Let us understand this with example:
JS Example
let student = [{
name: 'Tan',
score: 98
}, {
name: 'Jack',
score: 97
}, {
name: 'Racky',
score: 90
}];
console.log('Student = ',student.find(stu => stu.score > 90));
Output
Student = { name: 'Tan', score: 98 }
4. Array.findIndex()
In ES6, Findindex() is a new method added in Array. Prototype, it returns the index of the first element of the array which passes the condition, otherwise, returns -1 if no element of the array pass the condition.
Syntax
array.findIndex(callback( element[, index[, array]] )[, thisArg])
- Callback: This is a function to execute on each element of the array. The callback function takes these three-arguments.Element: it represents the current element.
- index: It represents the index of the current element.
- Array: It represents the array on we are calling the find() method.
- thisarg: It is an optional parameter. It is a value that is used as this while using callback.
JS Example
let animal = [{
name: 'caty',
weight: 14
}, {
name: 'racy',
weight: 10
}];
console.log('index of element = ',animal.findIndex(stu => stu.weight < 14));
Output
index of element = 1
5. Array.fill()
In ES6 Array. fill() gives us a simple way to fill given values to an array from start index(0) to end index(array. length) and return the modified array. It is a new method added in ES6 Array. prototype.
Note: We need to specify the position of the start and end of the filling. If we will not specify, then all elements will be filled in an array.
Syntax
array.fill(value[, start[, end]])
Parameters
- value: It static value to fill the array.
- start : It is an optional parameter and has default value 0.It specify the index to start filling the array
- End:It is optional parameter has default value is array.length.It is the index to stop filling the array.
1. JS array.fill() Example
let marks = [90, 80, 90];
marks.fill(100);
console.log(marks);
Output
[ 100, 100, 100 ]
In the above code, as we can see, we did not specify the start Index and end Index, So the fill() method overwrites all values of marks array to 100.
2. JS array.fill() Example by pass Start and end Index
let marks = [90, 80, 90,89,79];
marks.fill(100,2,4);
console.log('modified array = ',marks);
Output
modified array = [ 90, 80, 100, 100, 79 ]
6.Array.copyWithin()
In ES6 copyWithin() is a new method added in array.prototype.It copies values inside to another location in the same array and returns the modified array without making any modification to array length.
Syntax
array.copyWithin(target, start, end)
Parameters
- target : It represent the index position to copy the elements.
- Start: It is an optional parameter and represents the index at which to start copying elements. Its default value is 0. If this index is negative, the start will be counted from the end.
- End: It is an optional parameter, it represents the index at which to end copying elements.
JS array.copyWithin() example:
const marks = [80,90,100,90,70,100];
const english = [89,96,98,90,90,90,97,100];
const Maths = [100,100,100,94,95,96,99,98,90];
//did not specfiy start and end index
console.log('copying without start and end index =\n',marks.copyWithin(1));
//specfiy start index
console.log('\ncopying with start index = \n',english.copyWithin(1,3));
//specfiy start and end index
console.log('\n copying with start index and end index =\n ',Maths.copyWithin(1,3,5));
Output
copying without start and end index =
[ 80, 80, 90, 100, 90, 70 ]
copying with start index =
[
89, 90, 90, 90,
97, 100, 97, 100
]
copying with start index and end index =
[
100, 94, 95, 94, 95,
96, 99, 98, 90
]
7. Array.prototype.entries()
In ES6, Array. entries() is a new method added in the array. prototype. This method returns an Array Iterator object, used to loop over keys and values of arrays.
Entries() will return an iterator, in which every child array is an array of [index, value].
Syntax
array.entries()
JS array.entries() example
let subjects = ['Eng', 'Math', 'Music','Physis'];
var subject = subjects.entries();
for (sub of subject) {
console.log(sub);
}
Output
[ 0, 'Eng' ]
[ 1, 'Math' ]
[ 2, 'Music' ]
[ 3, 'Physis' ]
8. Array.prototype.keys()
It is similar to array.entries(), it returns an array iterator object, used to loop over keys.
Syntax
array.keys()
ExampleIn this code, to iterate over the keys we are using the spread operator indicate with three dots((…).
let subjects = ['Eng', 'Math', 'Music','Physis'];
var subject = subjects.keys();
console.log('keys = ',...subject);
Output
keys = 0 1 2 3
9. Array.prototype.values()
It is similar to array.entries(), it returns an array iterator object, used to loop over the values.
Example
In this example code, to iterate over the keys we are using the spread operator indicate with three dots((…).
let subjects = ['Eng', 'Math', 'Music','Physis'];
var subject = subjects.values();
console.log('values = ',...subject);
Output
keys = Eng Math Music Physis
Conclusion:
In this post, we learned the 9 new array functions added in ES6.I hope you will find them useful, these are great extensions to ES6 to make us achieve more in less code.