Es6 Array Functions
ES6 Array Methods
ES6HOME
Es6 provided us many cool functions which helps us to code better. So in this blog we are going to discuss some of the best array functions. These functions can help you to develop efficient code with reduced complexity. So let's get started!
concat() :
This method will combine two or more arrays and produce one single array object.
const arr1 = ['a','b','c'];
const arr2 = ['x','y','z'];
const arr3 = arr1.concat(arr2);
consol.log(arr3);
output:
['a','b','c','x','y','z'];
map():
This method operated on each element in the array, and finally produce the new array with results.
const arr1 = ['1','2','3'];
const arr2 = arr1.map((x) => x * 2);
output:
2,4,6
ES6HOME
filter():
This filter function reads each element of the array and compares it with the given condition and generates a new array with the filtered values.
const numbers = [4,2,3,5,7,6,9,8]; const arr = numbers.filter((number) => number > 5); console.log(arr);
indexOf()
returns the position of first occurrence of the given element in the array.
const cities = ['Delhi','Mumbai','Chennai','Hyderabad','Bangalore','Kolkata'];
console.log(cities.indexOf('Chennai')); console.log(cities.indexOf('Hyderabad',2)); console.log(cities.indexOf('Pune'));
Reduce():
const myArray = [1,2,3,4];
const reducer = (previousValue,currentValue) => previousValue+currentVal
console.log(myArray.reduce(reducer);
//1+2+3+4
o/p: 10
console.log(myArray.reduce(reducer,5);
//1+2+3+4+5
o/p: 15
MOVETOP↑
slice()
slice method returns the portion of an array in the for of array object selected from start to end position. The original array remain as it is.
const cities = ['Delhi','Mumbai','Chennai','Hyderabad','Bangalore','Kolkata'];
console.log(cities.slice(2));
o/p: Array['Hyderabad','Bangalore','Kolkata'];
console.log(cities.slice(2,5));
o/p: Array['Chennai','Hyderabad','Bangalore'];
Splice():
Splice method allows removing or replacing elements from the array.
array.splice(index, howMany, [element1][, ..., elementN]);
const cities = ['Delhi','Mumbai','Chennai','Hyderabad','Bangalore','Kolkata'];
cities.cities(1,0,"Jaipur");
adds the element at position 1.
Result:
['Delhi','Jaipur','Mumbai','Chennai','Hyderabad','Bangalore','Kolkata'];
Copy the above snippets in the script tag save the file in some folder and double click to open in browser and test the output.
TOP↑
demo.html
<!DOCTYPE html>
<html>
<body>
<h1>Function</h1>
<p>This demonstrates of popular array methods.</p>
<script>
...
</script>
</body>
</html>
ES6HOME
Comments
Post a Comment