As developers, dealing with arrays is a thing we just cannot do without. Whether it's a list of items in a shopping cart, or a list of users, or even a list of todo items, we regularly manipulate these to get various results.
The forEach method is normally used to loop through an array and perform a callback on each item. For example:
const students = ["James","Rita","Jean","Francis"] students.forEach(student => console.log(student)) // expected output: "James" // expected output: "Rita" // expected output: "Jean" // expected output: "Francis"
The map method works just like the forEach method with a little modification. While the forEach method simply runs the callback method, the map method returns a new array. For example:
const positiveIntegers = [1,3,4,5] const modified = positiveIntegers.map(i => i+2) console.log(positiveIntegers) console.log(modified) // expected output: [1,3,4,5] // expected output: [3,5,6,7]
The filter method works just like the name implies, it filters through a list and returns a new list based on the conditions supplied in the callback function. For example, lets get the students whose names do not begin with the letter a
const students = ["angel","angela","becky","james"] const filtered = students.filter(name => name !== "a") console.log(filtered) //expected output: ["james"]
The find method loops through an array and returns the first element that matches the condition provided in the callback. For example, let's get the first number that is greater than 5 in a list of numbers.
const numbers = [3,2,4,7,9,12,3] const matched = numbers.find(item => item > 5) console.log(matched) // returns 7