Method Chaining
There is an array of objects with names, scores and subjects attended by each student.
const students = [
{ name: "Mango", score: 83, courses: ["mathematics", "physics"] },
{ name: "Poly", score: 59, courses: ["informatics", "mathematics"] },
{ name: "Ajax", score: 37, courses: ["physics", "biology"] },
{ name: "Kiwi", score: 94, courses: ["literature", "informatics"] },
];
You need to get an array of their names sorted in ascending order by test scores. To do this, sort the array copy using the sort()
method, after which, using the map()
method, create an array of the name
property values from the sorted array.
const sortedByAscendingScore = [...students].sort((a, b) => a.score - b.score);
const names = sortedByAscendingScore.map(student => student.name);
console.log(names); // ['Ajax', 'Poly', 'Mango', 'Kiwi']
The problem is that you receive intermediate variables after each operation except the final one. The sortedByAscendingScore
variable is superfluous and is only needed to store the intermediate result.
You can get rid of such "dead" variables by grouping method calls into chains. Each next method will be executed based on the result of the previous one.
const names = [...students]
.sort((a, b) => a.score - b.score)
.map(student => student.name);
console.log(names); // ['Ajax', 'Poly', 'Mango', 'Kiwi']
- Make a copy of the original array before sorting.
- Call the
sort()
method on the copy. - Apply the
map()
method to the result of thesort()
method. - The variable
names
is assigned the result of themap()
method.
You will get an alphabetically sorted array of unique attended subjects.
const uniqueSortedCourses = students
.flatMap(student => student.courses)
.filter((course, index, array) => array.indexOf(course) === index)
.sort((a, b) => a.localeCompare(b));
console.log(uniqueSortedCourses); // ['biology', 'informatics', 'literature', 'mathematics', 'physics']
- Call
flatMap()
on the original array and create a flattened array of all courses. - Apply the
filter()
method to the result of theflatMap()
method in order to filter unique elements. - Call
sort()
on the result of thefilter()
method. - The variable
uniqueSortedCourses
is assigned the result of thesort()
method.
The method chain can be of arbitrary length, but usually no more than 2-3 operations. First, iteration methods are used for relatively simple collection operations. Second, calling each subsequent method is an additional array iteration, which, with a large number of elements, can affect performance.