Hello. I study JavaScript, read the textbook "Expressive JavaScript" and reached an interesting task at the end of the fifth chapter.
The task looks like this:
As a bonus game, write the groupBy function, which abstracts the grouping operation. It should take an array and a function that computes the group for the elements of the array, and return an object that matches the names of the groups to the arrays of the members of these groups.
I decided that I would write a prototyped method for arrays so that the array would be passed to the function as an array. массив.метод()
In general, here's the code, it works fine, everything works as it should. Brought you to the court, what do you say? Are there any obvious flaws and govnokod?
Array.prototype.groupBy = function(acto) { var tempObj = {}; //Создаем пустой объект for (var i=0; i<this.length; i++){ //Запускаем проход по массиву var temp = acto(this[i]); //Создаём переменную, куда помещаем результат вызова функции переданной аргументом. Условимся о том, что функция, передаваемая аргументом, должна возвращать строку if (!tempObj[temp]) { //Проверяем наш объект и если в нём нет свойства с таким именем, то tempObj[temp] = [this[i]]; //Создаём свойство с таким именем куда помещаем массив, в который, в свою очередь, помещаем элемент итерации } else { //Иначе tempObj[temp].push(this[i]); //в массив-свойство объекта добавляем результат операции } } return tempObj; //Возвращаем объект } Work example:
Array.prototype.groupBy = function(acto) { var tempObj = {}; //Создаем пустой объект for (var i = 0; i < this.length; i++) { //Запускаем проход по массиву var temp = acto(this[i]); //Создаём переменную, куда помещаем результат вызова функции переданной аргументом. Условимся о том, что функция, передаваемая аргументом, должна возвращать строку if (!tempObj[temp]) { //Проверяем наш объект и если в нём нет свойства с таким именем, то tempObj[temp] = [this[i]]; //Создаём свойство с таким именем куда помещаем массив, в который, в свою очередь, помещаем элемент итерации } else { //Иначе tempObj[temp].push(this[i]); //в массив-свойство объекта добавляем результат операции } } return tempObj; //Возвращаем объект } var arrayWithTrash = [1, 2, 3, "A", "B", "C", 4, 5, 6, true, [1, 2, 3], { "a": 250 }]; console.log( arrayWithTrash.groupBy(function(elemArray) { if (typeof elemArray === "number") return "Number"; else if (typeof elemArray === "string") return "String"; else if (typeof elemArray === "boolean") return "Boolean"; else return "Other"; }) ); .as-console-wrapper { min-height: 100% !important; top: 0; }