{"id":6643,"date":"2023-08-22T04:00:07","date_gmt":"2023-08-22T04:00:07","guid":{"rendered":"https:\/\/www.ardorsys.com\/blog\/?p=6643"},"modified":"2023-08-22T04:56:17","modified_gmt":"2023-08-22T04:56:17","slug":"array-methods-in-javascript-filter-find-map-reduce-every-and-some","status":"publish","type":"post","link":"https:\/\/www.ardorsys.com\/blog\/array-methods-in-javascript-filter-find-map-reduce-every-and-some\/","title":{"rendered":"Array Methods in JavaScript: Filter, Find, Map, Reduce, Every, and Some"},"content":{"rendered":"<p>Not everything is an object. When it comes to functional programming, it\u2019s more to do with the processes that get you from point A to point B than how data and groups of business logic are structured.<\/p>\n<p>JavaScript is a language that\u2019s prone to imperative patterns because of how easy it is to pick up. A lot of <a href=\"https:\/\/www.ardorsys.com\/hire-php-developer\/\">developers<\/a> tend to write their code in a procedural manner \u2014 where one blip in the procedure can break the code or create side-effect bugs.<\/p>\n<p>This is where functional patterns come in.<\/p>\n<h3 id=\"the-quick-lowdown-on-functional-programming\">The Quick Lowdown on Functional Programming<\/h3>\n<p>A lot of smelly JavaScript code is written in an imperative or procedural pattern. This is code that\u2019s written in a way that represents a flow of thought, resulting in a series of dependencies for the chain to work.<\/p>\n<p>Take a look at the procedural model below:<\/p>\n<pre><code>Start.\r\n\r\nCheck computer power status\r\nif on, proceed to next step. Else proceed to turn computer on.\r\nEnter password. If password accepted, proceed. Else try again.\r\nOpen browser. \r\nStart browsing the Internet.\r\n\r\nEnd.<\/code><\/pre>\n<p>Each step in the process needs to be done in order for the final outcome to occur. For some circumstances, a procedural pattern is necessary but it\u2019s not required for all scenarios.<\/p>\n<p>There are some scenarios where the order doesn\u2019t matter as much. For example, the task of making instant coffee. It doesn\u2019t matter in which order you put in the sugar and coffee powder \u2014 as long as it\u2019s in the mug. That\u2019s what <a href=\"https:\/\/www.ardorsys.com\/web-application-development\/\">functional programming<\/a> is in a nutshell.<\/p>\n<p>In JavaScript, we often work with arrays but a lot of developers tend to use an imperative pattern when it\u2019s not necessary.\u00a0<code>while<\/code>\u00a0and\u00a0<code>for<\/code>\u00a0loops may be used to filter, find or do something to each value inside the array.<\/p>\n<p>However, if something goes wrong, the process hasn\u2019t finished running, or the flow somehow breaks, the functions that depend on correct values will also break as a side effect.<\/p>\n<p><code>filter()<\/code>,\u00a0<code>find()<\/code>,\u00a0<code>map()<\/code>,\u00a0<code>reduce()<\/code>,\u00a0<code>every()<\/code>\u00a0and\u00a0<code>some()\u00a0<\/code>are six JavaScript array methods that should be used more often to prevent such blips from occurring. These methods are fantastic to use and read in code because<em>\u00a0they don\u2019t require a state to exist<\/em>\u00a0to work.<\/p>\n<h4 id=\"how-to-use-filter\">How to Use filter()<\/h4>\n<p><code>filter()<\/code>\u00a0is a method that lets you create a new array based on conditions that evaluate to\u00a0<code>true<\/code>\u00a0from an existing array.<\/p>\n<p>Take a look at the example below:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n   {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n   {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n   {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n ]\r\n\r\n \/*using imperative*\/\r\n let neuteredAnimals = [];\r\n\r\nfor (let i=0; i &lt; animals.length; i++){\r\n  let a = animals[i];\r\n  if(a.isNeutered){\r\n    neuteredAnimals.push(a);\r\n  }\r\n}<\/code><\/pre>\n<p>The above example is a procedural pattern we often see in the wild as a way to loop through each item in the array, test the condition then push it into the new array.<\/p>\n<p>With the\u00a0<code>filter()<\/code>\u00a0method, you just need to set the condition. For example:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\n \/*using functional filter() where a represents an item in the array*\/\r\n let neuteredAnimals = animals.filter((a) =&gt; {\r\n     return a.isNeutered;\r\n });<\/code><\/pre>\n<p>Here, we just need to set up the filter method against the array. The anonymous function lets\u00a0<code>a<\/code>\u00a0represent a single item in the array in the same manner as\u00a0<code>a = animals[i]<\/code>\u00a0did in the procedural pattern. Whatever is returned within the\u00a0<code>filter()<\/code>\u00a0is what gets put into the new array.<\/p>\n<h4 id=\"how-to-use-find\">How to use find()<\/h4>\n<p>In JavaScript,\u00a0<code>find()<\/code>\u00a0is used to create a new object based on the condition you set. On the surface, it looks like\u00a0<code>filter()<\/code>\u00a0but they\u2019re not the same.\u00a0<code>filter()<\/code>\u00a0returns an array of matched objects while\u00a0<code>find()<\/code>\u00a0will return the first matched object.<\/p>\n<p>See the example below:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\nanimalTypeFound = animals.find( animal =&gt; animal.type === 'cat' );\r\n\r\n\/\/ animalTypeFound will return:\r\n\/\/ {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2}\r\n\r\nanimalTypeFilter = animals.filter( animal =&gt; animal.type === 'cat' );\r\n\r\n\/\/ animalTypeFilter will return:\r\n\/\/ [{name: 'Tibbers', type: 'cat', isNeutered: true, age: 2}, {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}]\r\n<\/code><\/pre>\n<p><code>find()<\/code>will stop at the first match while\u00a0<code>filter()<\/code>\u00a0will continue and return all matched items in the array.<\/p>\n<h4 id=\"how-to-use-map\">How to Use map()<\/h4>\n<p>You have an array but you want it to look different. You could loop through using a\u00a0<code>forEach()<\/code>\u00a0function but that will only create complications later down the line.<\/p>\n<p>Mapping lets you move the values around, reassign them to different selectors and whatever else you want to do to them. The result of\u00a0<code>map()<\/code>\u00a0is an object that lets you store key-pair values or just an array of simple values.<\/p>\n<p>See the code below for syntax and examples:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\n\/\/ what you need: \r\n\/\/ ['Tibbers', 'Fluffball', 'Strawhat']\r\n\r\nlet animalNames = animals.map(animal =&gt; {return animal.name});\r\n\r\n\/\/ what you need: \r\n\/\/ [{name: 'Tibbers', species: 'cat'}, {name: 'Fluffball', species: 'rabbit'}, {name: 'Strawhat', species: 'cat'}]\r\n\r\nlet petDetails = animals.map(animal =&gt; {\r\n    return {\r\n        name: animal.name, \r\n        species: animal.type\r\n    };\r\n});<\/code><\/pre>\n<h4 id=\"how-to-use-reduce\">How to Use reduce()<\/h4>\n<p>We hear about\u00a0<code>reduce<\/code>\u00a0from time to time but no one really talks about what exactly it is. In short,\u00a0<code>reduce<\/code>\u00a0lets you interact two values or objects adjacent to each other from left to right.<\/p>\n<p>For example, you have the following array:\u00a0<code>[100, 20, 10]<\/code><\/p>\n<p>If you were to use\u00a0<code>reduce()<\/code>\u00a0on it, the first set of values will be\u00a0<code>100<\/code>\u00a0and\u00a0<code>20<\/code>. Then whatever the output of that is used to interact with\u00a0<code>10<\/code>.<\/p>\n<pre><code class=\"language-javascript\">let numbers = [100, 20, 10];\r\n\r\n\/\/ result will return 70 as the value\r\n\/\/ The function inside reduce will run twice. \r\n\/\/ the first time, x = 100, y = 20\r\n\/\/ the second time, x = 80, y = 10\r\n\r\nresult = numbers.reduce((x, y) =&gt; { return x - y; });<\/code><\/pre>\n<p><code>reduce()<\/code>\u00a0can also take two arguments. The first is the function that determines what happens to the two values and the second sets the starting value.<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\n\/\/ How old are all the animals combined?\r\n\/\/ 0 is the starting value and acts as the first acculmulator value\r\n\/\/ will return 8\r\n\r\nlet totalAge = animals.reduce((acculmulator, animal) =&gt; {\r\n    return acculmulator + animal.age;\r\n}, 0);\r\n\r\n\/\/ lets say you want to find out the oldest animal \r\n\/\/ code below will return {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n\r\nlet oldestPet = animals.reduce((oldest, animal) =&gt; {\r\n    return (oldest.age || 0) &gt; animal.age ? oldest : animal;\r\n  }, {});\r\n\r\n  \/\/ decrypting the code above and how terniaries work \r\n  \/\/ the condition --&gt; (oldest.age || 0) &gt; animal.age \r\n  \/\/ if true --&gt; ? oldest\r\n  \/\/ else --&gt; : animal<\/code><\/pre>\n<h4 id=\"how-to-use-every\">How to Use every()<\/h4>\n<p>Every returns a\u00a0<code>true<\/code>\u00a0or\u00a0<code>false<\/code>\u00a0value based on the condition set. It works in a similar fashion as\u00a0<code>filter()<\/code>\u00a0but instead of returning an object or value,\u00a0<code>every()<\/code>\u00a0spits back a boolean.<\/p>\n<p>This makes it good for quickly checking whether everything inside an array meets the criteria.<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\nlet allNeutered = animals.every(animal =&gt; {return animal.isNeutered});\r\n\r\n\/\/will return false because not all values under isNeutered evaluates to true<\/code><\/pre>\n<h4 id=\"how-to-use-some\">How to use some()<\/h4>\n<p><code>some()<\/code>\u00a0works the same way as\u00a0<code>every()<\/code>\u00a0but only at least one of the conditions needs to evaluate to\u00a0<code>true.<\/code><\/p>\n<p>See example below:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5}\r\n  ]\r\n\r\nlet someAreCats = animals.some(animal =&gt; {return animal.type === 'cat'});\r\n\r\n\/\/ will return true because at least one animal.type returned 'cat'<\/code><\/pre>\n<p>In real-world use cases, you might use\u00a0<code>every()<\/code>\u00a0and\u00a0<code>some()<\/code>\u00a0to check values in an array before sending them off to the database.<\/p>\n<p>Or perhaps you want to make sure that there is a certain category of an item in a cart before applying a special discount. Or you\u2019re coding a booking system and you wanted to make sure that every customer who can book satisfies the minimum age requirements.<\/p>\n<h4 id=\"lets-mix-and-match\">Lets Mix and Match!<\/h4>\n<p>You can use these array methods on their own or in chains. The result from the first method will be used as the value for the following method.<\/p>\n<p>See the example below:<\/p>\n<pre><code class=\"language-javascript\">let animals = [\r\n    {name: 'Tibbers', type: 'cat', isNeutered: true, age: 2, enteredPagent: true, cutenessScore: 347},\r\n    {name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1, enteredPagent: true, cutenessScore: 193},\r\n    {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5, enteredPagent: false, cutenessScore: 521}\r\n  ]\r\n\r\n\/\/lets say you want to find the total cuteness score of all valid pagent entrants\r\n\r\nlet totalScore = animals\r\n                    .filter(animal =&gt; {return animal.isNeutered})\r\n                    .reduce((accumulator, animal) =&gt; {return accumulator + animal.cutenessScore}, 0);\r\n\r\n\/\/ totalScore will return 868<\/code><\/pre>\n<p>Depending on your dataset, you can become quite efficient with arrays, reducing the need to manually loop through every object and array to do what you need to do.<\/p>\n<h4 id=\"final-words\">Final Words<\/h4>\n<p>JavaScript can be efficient \u2014 if you take the time to learn it properly. Developers new to JavaScript tend to fall into procedural patterns because it\u2019s easy.<\/p>\n<p>However, easy can quickly turn into a spaghetti jumble of complicated once you work with more than one\u00a0<code>for<\/code>\u00a0or\u00a0<code>while<\/code>\u00a0loop. Array methods eliminate the potential craziness that comes with long code, nested brackets and, lost semi-colons.<\/p>\n<p style=\"font-size: 13px;\">Source: <a href=\"https:\/\/www.dottedsquirrel.com\/array-methods-javascript\/\" target=\"_blank\" rel=\"nofollow noopener\">Dottedsquirrel<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"JavaScript is a language that\u2019s prone to imperative patterns because of how easy it is to pick up. A lot of developers tend to write their code in a procedural manner \u2014 where one blip in the procedure can break the code or create side-effect bugs.\n","protected":false},"author":1,"featured_media":6644,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[150],"tags":[152,151],"class_list":{"0":"post-6643","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"tag-array","9":"tag-javascript"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6643","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/comments?post=6643"}],"version-history":[{"count":2,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6643\/revisions"}],"predecessor-version":[{"id":7249,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6643\/revisions\/7249"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media\/6644"}],"wp:attachment":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media?parent=6643"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/categories?post=6643"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/tags?post=6643"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}