Thursday, February 23, 2023
HomeSoftware DevelopmentThe way to use map(), filter(), and cut back() in JavaScript ?

The way to use map(), filter(), and cut back() in JavaScript ?


The map(), filter(), and cut back() are the array features that enable us to govern an array in line with our personal logic and return a brand new array after making use of the modified operations on it. These strategies are very fashionable amongst JavaScript builders as they make the code quick, easy, and clear. These array features change the normal method of iterating an array utilizing for loop. These strategies are also referred to as increased order features. These strategies use a callback perform to implement the logic

JavaScript map() Technique: This technique is used to use a specific operation on every aspect of the array in a callback perform after which return the up to date array

Syntax:

arr.map(perform(args){
    ...
})

Instance: On this instance, we’ll use the map() technique so as to add 2 to every array aspect

Javascript

var arr= [2,4,8,10]

var updatedArr = arr.map(val=> val+2)

console.log(arr);

console.log(updatedArr);

Output:

(4) [2, 4, 8, 10]
(4) [4, 6, 10, 12]

JavaScript filter() Technique: This technique is used to return an array that comprises the weather which fulfill the situation utilized contained in the callback perform

Syntax:

arr.filter(perform(){
    // situation
}) 

Instance: On this instance, we’ll use the filter() technique to get the weather smaller than 5 in an array.

Javascript

var arr= [2,4,8,10]

var updatedArr = arr.filter(val=> val<5)

console.log(arr);

console.log(updatedArr);

Output:

(4) [2, 4, 8, 10]
(2) [2, 4]

JavaScript cut back() Technique: This technique is used to use a callback perform to every aspect in an array and return a single aspect

Syntax:

arr.cut back(perform(){
    ...
}) 

Instance: On this instance, we’ll use cut back() technique to calculate the sum of the array.

Javascript

var arr= [2,4,8,10]

var updatedArr = arr.cut back((prev, curr)=> curr= prev+curr)

console.log(arr);

console.log(updatedArr);

Output

(4) [2, 4, 8, 10]
24

The desk under exhibits the comparability of properties of the above-mentioned strategies:

Property

map()

filter()

cut back()

Return kind Returns a brand new array Returns a brand new array Returns a single aspect
Motion Modifies every aspect of the array Filter out the aspect which passes the situation Reduces array to a single worth
Parameters worth, index, array worth, index, array accumulator, worth, index, array

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments