Making a sum with lodash _.sum, _.reduce, and vanilla javaScript alternatives
Creating a sum from an array, more often then not, is a fairly trivial matter with javaScript as it can quickly be done with a native array method like reduce. However in some cases it might be nice to have methods that make quick work of trivial tasks such as this by allowing me to just call a single method for this and move forward with a project that much faster.
Making a native sum method might not be so hard, however if lodash is there to work with in a project then that can be called to quickly create a sum for an array of numbers. In this post I will be writing about _.sum, _.sumBy, _.reduce when it comes to working in a project in which lodash is there to work with. However because lodash seems to be on its way out there is also looking into vanilla js alternatives when creating a sum from an array of numbers.
1 — what to know before hand
This is a post on using lodash to help with tasks involving summation, as well as plain javaScript examples of doing so as well. This is not a getting started post on lodash, or javaScript in general so I assume that you have at least some background with these topics.
In this section I will be going over a few quick things that you should maybe know about before hand before continuing to read the rest of this post. As you might expect this is the section with very basic examples intended for people that are still relatively new to javaScript. So if you have some experience you might consider skipping over this part to get to the good stuff.
— version numbers matter
In this post I was using lodash 4.17.10
— The source code examples here are on Github
I have the source code examples here in my test lodash github respiratory. I am working on more examples for this post so it is possible that the examples there might be a bit more up to date. In any case there are some additional notes, lists, and it is also a good place to make a pull request if you see something wrong with the code examples here. It is also where I hold my source code examples for all my other posts on lodash for what they are worth.
1.1 — Basic while loop sum example
Just looping over the contents of an array that just happens to be an array of numbers, and only numbs to add up all the values is simple enough. One of many ways would be to use a while loop and set the starting index at the length of the array to add up and loop backwards. Then fore each element I just use the assignment and addition operators to add the current number value of an array element to a sum variable.
1.2 — Using the lodash sum method
If lodash is there to work with in a project the lodash sum method can be used to quickly sum up the values of an array though. The use of it is also pretty simple I juts call the method and pass the array as the first and only argument and the return value is then the sum.
However what if there are some additional steps that need to happen in order to have an array of numbers to begin with? Also what if some of the elements are not numbers but string values of numbers? So then maybe just the lodash sum method alone is not all that big of a deal as to support a case to continue using lodash, but maybe things will be at least a little more convincing when looking into some more complex use case examples.
1.3 — Looking out of things surrounding types
One thing to be aware of when adding up the numbers of an array is to make sure that you are in fact dealing with numbers. There are also some things to be aware of when it comes to numbers in javaScript including a weird kind of number known as Not a Number (NaN). So in this example I am using the javaScript typeof operator along with some additional expressions and if statement to create a parse element method.
There is then trying out both the while loop approach and the lodash sum method approach with this parse element method. When it comes to the while loop approach I can just call them method inside the body of the while loop and use the returned result of calling the parse element method as the number to add to the sum rather than just directly adding values of the source array many of which are not numbers. When it comes to using lodash I can call the main lodash function and pass the array are the argument to it, I can then call the lodash map method and pass my parse element method to the lodash map method, after that I can then call the sum method all in a single line.
2 — Using lodash to add up a sum
So there are a number of methods in lodash that can be used to add up a sum, such as _.sum which can be used to quickly add up the numbers of an array which I touched base on in the basic section. In addition summation can also easily be done with a number of additional methods in lodash like _.reduce, and _.forEach just to name a few options to chose from. Some of these methods might be methods that take an array as the first argument like that of the lodash sum method, but many of them are collection methods. What is cool about these methods is that they will work not just with arrays, but with objects in general. So then in this section I will be going over a few more options to take into account when it comes to using lodash, before moving on to other topics including vanilla javaScript solutions for creating sums.
2.1 — Using _.sum to just add an array of numbers
Using the _.sum method is easy enough when it comes to an array of primitive numbers at least. In that case just pass the array of numbers to it and you sum of those numbers will be returned as I did in the basic section. I also covered another examples in that section that makes use of a few more lodash features to handing other kinds of arrays that contains types other than that of numbers.
So maybe some times I do just have an array of numbers to being with and when that is the case yes it is not so hard to just add them up with lodash or just plain javaScript alone. Although I most real world examples I can not say that I often deal with an array that is formated like that to begin with, I must first produce an array of numbers by which to sum. In some cases I might have an array of objects for example and I must loop over each object adding up one or more properties and ignoring others. Not to worry there are other methods that can be used together with the lodash sum method to deal with most of those situations, and the lodash map method is just one such method.
2.2 — Using _.sumBy for an array of objects
Say I have a not just an array of numbers, but an array of objects, and I need to make a sum by preforming an operation for each object. For example say I have an array of objects where each object is a report for sales and expenses for a certain business day. I want to add up how much profit has been made for each day, so I will need to subtract expenses from sales and then add that result up for each day. This can be done with _.sumBy lodash method in a very quick and easy manor.
2.3 — Using _.reduce
The _.reduce method can be used to create a sum fairly quickly as well when it comes to yet event another lodash method. What is nice about lodash reduce compared to lodash sum is that reduce in lodash is one of the many collection methods of lodash where is sum is a method that will only work with arrays.
2.4 — Do not forget about the power of chaining
So if you are using the full lodash library then there are all the methods that lodash has to offer that can be used to help with the process of working out a more complicated task involving a sum. The lodash methods like groupBy can be used in conjunction with others like _.map with Implicit Chaining.
Say you have a bunch of objects that share a common value, and I want all objects that share that value summed up I could pull that off by doing something like this.
3 — Vanilla javaScript examples
Now for some plain vanilla JavaScript examples of how to add things up. Lodash is a great project with many useful methods, but it is also true that making a sum is really not all that hard to do with just plain old javaScript. In this section I will be looking at native equivalents to methods like _.reduce as well as other features that are part of native javaScript by itself.
3.1 — Just using a loop
Noting wrong with just using a for a while loop that is what they are there for. When using a while loop there is the trick of setting an index value to the length of an array and then subtracting from the index variable that is also evaluated in the while loop. This works because the number zero evaluates to false.
For example I can use that to quickly make a method that will figure an average of an array of numbers like this.
Working out something with a while loop is fine, but there are a number of other prototype methods, as well as static methods to be aware of when it comes to doing this sort of thing.
3.1 — Using Array.forEach or a loop
Using a native method like Array.forEach can be useful for quickly adding up some numbers in an array. This basic array prototype method works by just calling the for each method off of an array, and then passing a function that I want to call for each element in the array. Inside the body of the function that I pass to array for each the first argument will be the current number value for which the function is being called. So then I just need to create a sum variable then call array for each off of the array and add to the sum variable inside the function that I given to array for each.
The for each method is a nice little method for looping over an array, but there are many other similar methods in the array, some of which might prove to be a better choice for making a sum.
3.2 — The Array reduce method is also a good choice for making sums
Maybe one of the best options when it comes to array prototype methods would be the array reduce method. This method might be a little confusing when compared to other array prototype methods like for each at first but once one gets the basics of how to use it, the method comes in handy often such as when making some kind of sum value from an array of values.
The basic idea of making a sum with array reduce would be to call the array reduce method off of the array to which I want to make a sum from and then pass a reduce function as the first argument, and set a starting value for an accumulator to zero with the second argument for array reduce. The reduce function will then have an accumulator value for the first argument, and then the value of a current element as the second argument. Inside the body of the reduce function I just need to return the new value for the accumulator value with would be the sum of the accumulator plus the current element assuming that I will always be dealing with an array of numbers anyway.
4 — Objects in general and making a sum
Many of the methods in lodash are so called collection methods in the sense that they will work with objects in general, not just arrays. Sadly it would seem that the sum method is not once such method as the expected value that is passed to it needs to be an array. However it is often not so hard to convert say an array like object to an array, or some custom object with named keys to an array. The hard part is just furnishing an array of numbers first, and once that is done that of course can be passed to the lodash sum method, or one of the native options can be used. SO in this section I will be quickly going over some examples of making a sum from various kinds of objects other then that of an array in javaScript.
4.1 — Array like objects and Function.call
If you are not familiar with the function prototype methods such as apply, bind, and call then it might be a good idea to take a moment to look into them at this point. Often I find myself in a situation in which I am dealing with some kind of array like object. What I mean by that is that I am dealing with an object that is formated like an array, in that it has numbered rather than named keys, and a length property. However it is an array like because it is a plain object, or an object of a prototype other than that of Array. So then I can not just call array prototype methods like reduce off of such objects. However I can call the call function prototype method off of the array reduce prototype method and pass the array like object as the first argument to the call method, after that I can pass arguments as if I am using array reduce.
4.2 — Objects.values
Yet another method to keep in mind when using objects in general is the Object.values static method. This static method can be used to take an object and return an array of value for each public key. If each public key value is a number that I want to create a sum from this will then work to give me an array of numbers to which I can then pass to lodash sum, or use one of the native options.
4.3 — Object.keys
There is also the Object.keys static method that is just like Object.values only it will return an array of keys rather than values. This will just be the public keys of the object and is thus the same result as if I where to create this kind of array using something like a for in loop.
5 — Arrays of Arrays
Another topic that might come up when it comes to sums is how to go about making a sum of arrays of arrays, or a multidimensional array. When it comes to these kinds of arrays they can not just be passed to the lodash sum method. However there are a number of methods that can be used in lodash to help with this kinds of arrays mainly the lodash flatten methods.
5.1 — lodash flatten and sum methods
So if we are talking about just one more level then the lodash flatten method can be used to get a flattened array. The it is just a matter of passing the flattened array to the lodash sum method.
5.2 — lodash flatten deep method for more then 2 dimensions
If I am dealing with more than one level I can use the flatten deep method. There is then yet one more additional method to be aware of that is the flatten depth method that cane be used as a way to set how many levels should be fattened. These methods are then useful when I have many levels that I need to merge down into a single array that I can the use with the sum method.
6 — Conclusion
So in lodash there are some methods that can be used to quickly produce a sum, as well as other methods that can be used to add up a sum as well although they are not there for that purpose alone. With native javaScript there might not be a native sum method in the array prototype, but it is not to hard to make a sum with javaScript alone when it comes to using the native array reduce method for example. On top of that the lodash sum method is not a collection method, so in some cases one might still know how to convert certain types of objects to arrays first.
Методы массива JS
Массивы предоставляют множество методов. Чтобы было проще, в этой главе они разбиты на группы.
Добавление/удаление элементов#
Метод splice( )#
Как удалить элемент из массива?
Так как массивы – это объекты, то можно попробовать delete:
Вроде бы, элемент и был удалён, но при проверке оказывается, что массив всё ещё имеет 3 элемента arr.length == 3 .
Это нормально, потому что всё, что делает delete obj.key – это удаляет значение с данным ключом key . Это нормально для объектов, но для массивов мы обычно хотим, чтобы оставшиеся элементы сдвинулись и заняли освободившееся место. Мы ждём, что массив станет короче.
Поэтому для этого нужно использовать специальные методы.
Метод arr.splice(str) – это универсальный «швейцарский нож» для работы с массивами. Умеет всё: добавлять, удалять и заменять элементы.
Он начинает с позиции index , удаляет deleteCount элементов и вставляет elem1, . elemN на их место. Возвращает массив из удалённых элементов.
Этот метод проще всего понять, рассмотрев примеры.
Начнём с удаления:
Легко, правда? Начиная с позиции 1, он убрал 1 элемент.
В следующем примере мы удалим 3 элемента и заменим их двумя другими.
Здесь видно, что splice возвращает массив из удалённых элементов:
Метод splice также может вставлять элементы без удаления, для этого достаточно установить deleteCount в 0 :
Отрицательные индексы разрешены
В этом и в других методах массива допускается использование отрицательного индекса. Он позволяет начать отсчёт элементов с конца, как тут:
Метод slice( )#
Метод arr.slice намного проще, чем похожий на него arr.splice.
Он возвращает новый массив, в который копирует элементы, начиная с индекса start и до end (не включая end). Оба индекса start и end могут быть отрицательными. В таком случае отсчёт будет осуществляться с конца массива.
Это похоже на строковый метод str.slice , но вместо подстрок возвращает подмассивы.
Можно вызвать slice и вообще без аргументов: arr.slice() создаёт копию массива arr. Это часто используют, чтобы создать копию массива для дальнейших преобразований, которые не должны менять исходный массив.
Метод concat( )#
Метод arr.concat создаёт новый массив, в который копирует данные из других массивов и дополнительные значения.
Он принимает любое количество аргументов, которые могут быть как массивами, так и простыми значениями.
В результате мы получаем новый массив, включающий в себя элементы из arr , а также arg1, arg2 и так далее…
Если аргумент argN – массив, то все его элементы копируются. Иначе скопируется сам аргумент.
Обычно он просто копирует элементы из массивов. Другие объекты, даже если они выглядят как массивы, добавляются как есть:
…Но если объект имеет специальное свойство Symbol.isConcatSpreadable , то он обрабатывается concat как массив: вместо него добавляются его числовые свойства.
Для корректной обработки в объекте должны быть числовые свойства и length :
Метод forEach( )#
Метод arr.forEach позволяет запускать функцию для каждого элемента массива.
Например, этот код выведет на экран каждый элемент массива:
А этот вдобавок расскажет и о своей позиции в массиве:
Результат функции (если она вообще что-то возвращает) отбрасывается и игнорируется.
Поиск в массиве#
Методы indexOf/lastIndexOf и includes#
Далее рассмотрим методы, которые помогут найти что-нибудь в массиве. Методы arr.indexOf, arr.lastIndexOf и arr.includes имеют одинаковый синтаксис и делают по сути то же самое, что и их строковые аналоги, но работают с элементами вместо символов:
arr.indexOf(item, from)#
arr.lastIndexOf(item, from)#
arr.includes(item, from)#
Обратите внимание, что методы используют строгое сравнение === . Таким образом, если мы ищем false , он находит именно false , а не ноль .
Если мы хотим проверить наличие элемента, и нет необходимости знать его точный индекс, тогда предпочтительным является arr.includes .
Кроме того, очень незначительным отличием includes является то, что он правильно обрабатывает NaN в отличие от indexOf/lastIndexOf :
Методы find и findIndex#
Представьте, что у нас есть массив объектов. Как нам найти объект с определённым условием?
Здесь пригодится метод arr.find .
Его синтаксис таков:
Функция вызывается по очереди для каждого элемента массива:
- item – очередной элемент.
- index – его индекс.
- array – сам массив.
Если функция возвращает true , поиск прерывается и возвращается item . Если ничего не найдено, возвращается undefined .
Например, у нас есть массив пользователей, каждый из которых имеет поля id и name . Попробуем найти того, кто с id == 1 :
В реальной жизни массивы объектов – обычное дело, поэтому метод find крайне полезен.
Обратите внимание, что в данном примере мы передаём find функцию item => item.id == 1 , с одним аргументом. Это типично, дополнительные аргументы этой функции используются редко.
Метод arr.findIndex – по сути, то же самое, но возвращает индекс, на котором был найден элемент, а не сам элемент, и -1, если ничего не найдено.
Метод filter( )#
Метод find ищет один (первый попавшийся) элемент, на котором функция-колбэк вернёт true .
На тот случай, если найденных элементов может быть много, предусмотрен метод arr.filter(fn) .
Синтаксис этого метода схож с find , но filter возвращает массив из всех подходящих элементов:
Преобразование массива#
Перейдём к методам преобразования и упорядочения массива.
Метод map( )#
Метод arr.map является одним из наиболее полезных и часто используемых.
Он вызывает функцию для каждого элемента массива и возвращает массив результатов выполнения этой функции.
Например, здесь мы преобразуем каждый элемент в его длину:
Метод sort( )#
Вызов arr.sort() сортирует массив на месте, меняя в нём порядок элементов.
Он возвращает отсортированный массив, но обычно возвращаемое значение игнорируется, так как изменяется сам arr.
Не заметили ничего странного в этом примере?
Порядок стал 1, 15, 2 . Это неправильно! Но почему?
По умолчанию элементы сортируются как строки.
Буквально, элементы преобразуются в строки при сравнении. Для строк применяется лексикографический порядок, и действительно выходит, что "2" > "15" .
Чтобы использовать наш собственный порядок сортировки, нам нужно предоставить функцию в качестве аргумента arr.sort() .
Функция должна для пары значений возвращать:
Например, для сортировки чисел:
Теперь всё работает как надо.
Давайте возьмём паузу и подумаем, что же происходит. Упомянутый ранее массив arr может быть массивом чего угодно, верно? Он может содержать числа, строки, объекты или что-то ещё. У нас есть набор каких-то элементов. Чтобы отсортировать его, нам нужна функция, определяющая порядок, которая знает, как сравнивать его элементы. По умолчанию элементы сортируются как строки.
Метод arr.sort(fn) реализует общий алгоритм сортировки. Нам не нужно заботиться о том, как он работает внутри (в большинстве случаев это оптимизированная быстрая сортировка). Она проходится по массиву, сравнивает его элементы с помощью предоставленной функции и переупорядочивает их. Всё, что остаётся нам, это предоставить fn , которая делает это сравнение.
Кстати, если мы когда-нибудь захотим узнать, какие элементы сравниваются – ничто не мешает нам вывести их на экран:
В процессе работы алгоритм может сравнивать элемент с другими по нескольку раз, но он старается сделать как можно меньше сравнений.
Функция сравнения может вернуть любое число
На самом деле от функции сравнения требуется любое положительное число, чтобы сказать «больше», и отрицательное число, чтобы сказать «меньше».
JavaScript: 6 Ways to Calculate the Sum of an Array
This practical, succinct article walks you through three examples that use three different approaches to find the sum of all elements of a given array in Javascript (suppose this array only contains numbers). Without any further ado, let’s get started.
Using Array.reduce() method
If you’re using modern Javascript (ES6 and beyond), this might be the neatest and quickest solution.
Example:
Output:
The reduce() method executes a reducer function for elements of an array. It returns the accumulated result from the last call of the callback function. Below is the syntax:
Where:
- total (required): The initial value, or the previously returned value of the function
- current (required): The current element
- current (optional): The index of the current element
- arr (optional): The array that the current element belongs to
Javascript is interesting, and it also has another method quite similar to the reduce() method, named reduceRight() . You can get the sum of a numeric array with only a single line of code like this:
Output:
Using a classic For loop
This is an easy-to-understand approach and has been used for decades. However, the code is a bit longer.
Example:
Output:
Using modern For/Of loop
This approach also uses a loop but is more concise than the previous one. Like the Array.reduce() method, for/of was added to ES6 (JS 2015).
Example:
Output:
Using the map() method
The Array.map() method is new in ES6 and beyond. This one is very useful when you have to deal with an array, including finding the sum of its elements.
Example:
Output:
Using a While loop
Another way to sum the elements of an array for your reference (basically, it’s quite similar to other methods of using loops).
Example:
Output:
Using a forEach loop
Just another kind of loop in Javascript. Here’s how to make use of it to calculate the total value of a given array:
Output:
Conclusion
We’ve walked through several ways to get the sum of all elements of a given array in Javascript. Although just one method is enough, knowing the existence of other methods also helps you a lot in mastering the art of programming. Good luck and happy coding!
How to get the sum of an array in JavaScript
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
In this shot, we will discuss three methods you can use to get the total of a given array in JavaScript.
First, we’ll use the traditional for loop. Secondly, we’ll use forEach , an array-like method, and lastly, we’ll make use of for. of .
In this shot, our array example is [1, 4, 0, 9, -3] , and the expected output is 11 .
1. Using the traditional for loop
In this method, you iterate and add each item until you reach the last item.