Array (not)Fun-ctions
Hello, Welcome to my first ever technical blog. In this post, I will try to explain something that I really have trouble working on but then again I am just a naive coder atm. So, lets begin from a very basic concept called array. An array is a data structure which contains a collection of information each identified by an array index. Now, there are various operations which can be performed on array as per needed. Here are few array functions which I have worked on.
- Array.prototype.map(): This function is used to create a new array by applying an operation to each element in an already existing array. For example:
const array = [1, 2, 3];
const newArray = array.map((num) => num * 2);
console.log(newArray); // [2, 4, 6]2. Array.prototype.filter(): This function is used to create a new array which will contain the elements that pass a certain operations or conditions specified by a function.
const array = [1, 2, 3];
const newArray = array.filter((num) => num > 1);
console.log(newArray); // [2, 3]3. Array.prototype.reduce(): This function is used to reduce an array to a single value by applying a function to each element in the array. For example:
const array = [1, 2, 3];Get Harpreet Singh’s stories in your inbox
Join Medium for free to get updates from this writer.
const sum = array.reduce((total, num) => total + num, 0);
console.log(sum); // 6
4. Array.prototype.find(): This function is used to find the first element in an array that passes a certain condition specified by a function. For example:
array.find(function(currentValue, index, array) {
// code to test each element
});const array = [1, 2, 3];
const foundElement = array.find((num) => num > 1);
console.log(foundElement); // 25. Array.prototype.forEach(): It is an array function used to loop through an array and perform a certain action on each element. For example:
array.forEach(function(currentValue, index, array) {
// code to be executed on each element
});const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});





