Arrays are one of the fundamental and most useful data structures in programming. They are the building blocks of applications and serve as a foundation for more advanced data structures.
Every serious programmer should strive to master Arrays.
The forEach method is simple yet powerful: you provide a function that will execute once for each array element in ascending order.
An example to illustrate:
const array1 = ['read', 'clap', 'follow','share']; array1.forEach(element => console.log(element)); // expected output: "read" // expected output: "clap" // expected output: "follow" // expected output: "share"
As displayed above, the forEach method is primarily used when you want to iterate through an array.
The sort method sorts the elements of an array. The default sort order is ascending.
Important: the array elements are first converted into strings and are then compared based on UTF-16 code unit values.
const actions = ['read', 'clap', 'follow','share']; actions.sort(); console.log(actions); // expected output: ['clap', 'follow', 'read', 'share'] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: [1, 100000, 21, 30, 4]
To modify this default behaviour, we can supply a compare() function with the following in mind:
If compare(a, b) returns less than 0, sort a to an index lower than b (a should come before b).
If compare(a, b) returns 0, a and b have the same priority and order remains unchanged.
If compare(a, b) return greater than 0, sort b to an index lower than a (b should come before a).
const array1 = [1, 30, 4, 21, 100000]; array1.sort((a, b) => a - b); console.log(array1); // expected output: [1, 4, 21, 30, 100000]
Of course, the compare() function can be modified to:
- Sort in descending order.
- Sort objects.
The map function creates a new array as the result of calling a callback function for each element in the array in ascending order.
const array = [1, 2, 3, 4]; // pass a function to map const newArray = array.map(x => x * 10); console.log(array); // [1, 2, 3, 4] console.log(newArray); // [10, 20, 30, 40]
The difference between map() and forEach() is that map() returns the value returned by the callback function. While forEach(), does not do anything with the value returned by the callback.
The filter function return a new array of elements that pass a test implemented by the provided function.
const words = ['read', 'clap', 'criticize', 'follow', 'bad-mouth','share']; const result = words.filter(word => word.length < 7); console.log(words); // expected output: ['read', 'clap', 'criticize', 'follow', 'bad-mouth','share'] console.log(result); // expected output: ['read', 'clap', 'follow', 'share']