<p>I would like to filter an array of items by using the <code>map()</code> function. Here is a code snippet:</p>

<pre><code>var filteredItems = items.map(function(item)
{
    if( ...some condition... )
    {
        return item;
    }
});
</code></pre>

<p>The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.</p>

<p>Any idea?</p>

<p>EDIT: Thanks, I forgot about <code>filter()</code>, what I wanted is actually a <code>filter()</code> then a <code>map()</code>.</p>

<p>EDIT2: Thanks for pointing that <code>map()</code> and <code>filter()</code> are not implemented in all browsers, although my specific code was not intended to run in a browser.</p>

[{'answer_id': 9295, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 4, 'selected': False, 'text': '<p>That\'s not what map does. You really want <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow noreferrer"><code>Array.filter</code></a>. Or if you really want to remove the elements from the original list, you\'re going to need to do it imperatively with a for loop.</p>\n'}, {'answer_id': 9297, 'author': 'olliej', 'author_id': 784, 'author_profile': 'https://Stackoverflow.com/users/784', 'pm_score': 8, 'selected': True, 'text': '<p>You should use the <code>filter</code> method rather than map unless you want to mutate the items in the array, in addition to filtering.</p>\n\n<p>eg.</p>\n\n<pre><code>var filteredItems = items.filter(function(item)\n{\n    return ...some condition...;\n});\n</code></pre>\n\n<p>[Edit: Of course you could always do <code>sourceArray.filter(...).map(...)</code> to both filter and mutate]</p>\n'}, {'answer_id': 9329, 'author': 'ggasp', 'author_id': 527, 'author_profile': 'https://Stackoverflow.com/users/527', 'pm_score': 1, 'selected': False, 'text': '<p>You must note however that the <code>Array.filter</code> is not supported in all browser so, you must to prototyped:</p>\n\n<pre><code>//This prototype is provided by the Mozilla foundation and\n//is distributed under the MIT license.\n//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license\n\nif (!Array.prototype.filter)\n{\n    Array.prototype.filter = function(fun /*, thisp*/)\n    {\n        var len = this.length;\n\n        if (typeof fun != "function")\n            throw new TypeError();\n\n        var res = new Array();\n        var thisp = arguments[1];\n\n        for (var i = 0; i &lt; len; i++)\n        {\n            if (i in this)\n            {\n                var val = this[i]; // in case fun mutates this\n\n                if (fun.call(thisp, val, i, this))\n                   res.push(val);\n            }\n        }\n\n        return res;\n    };\n}\n</code></pre>\n\n<p>And doing so, you can prototype any method you may need. </p>\n'}, {'answer_id': 1498642, 'author': 'vsync', 'author_id': 104380, 'author_profile': 'https://Stackoverflow.com/users/104380', 'pm_score': 3, 'selected': False, 'text': '<h1>Array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow noreferrer">Filter method</a></h1>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [1, 2, 3]\r\n\r\n// ES5 syntax\r\narr = arr.filter(function(item){ return item != 3 })\r\n\r\n// ES2015 syntax\r\narr = arr.filter(item =&gt; item != 3)\r\n\r\nconsole.log( arr )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 36557522, 'author': 'Kyle Baker', 'author_id': 4526479, 'author_profile': 'https://Stackoverflow.com/users/4526479', 'pm_score': 6, 'selected': False, 'text': '<p>Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend <a href="http://code.kylebaker.io/2018/03/16/stack-overflow/" rel="noreferrer">checking that out</a> if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.</p>\n<p>That said, **The tl;dr is this:</p>\n<h2>To accomplish what you\'re asking for (filtering and mapping within one function call), you would use <code>Array.reduce()</code>**.</h2>\n<h2>However, the <em>more readable</em> <strong>and</strong> (less importantly) <em>usually significantly faster</em><sup><a href="http://code.kylebaker.io/2018/03/16/stack-overflow/#What-about-performance" rel="noreferrer">2</a></sup> approach is to just use filter and map chained together:</h2>\n<p><code>[1,2,3].filter(num =&gt; num &gt; 2).map(num =&gt; num * 2)</code></p>\n<p>What follows is a description of how <code>Array.reduce()</code> works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.</p>\n<hr />\n<p>You give reduce an argument that is a (usually anonymous) function.</p>\n<p><em>That anonymous function</em> takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is <strong>the value that will be passed along between function calls, often referred to as the <em>memo</em></strong>.</p>\n<p>Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for \'memo\' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then \'memo\' in the first anonymous function call will by default be the first iteratee, and the \'iteratee\' argument will actually be the second value in the array)</p>\n<p>In our case, we\'ll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.</p>\n<p>Finally, we\'ll return our \'array in progress\' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.</p>\n<p>This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.</p>\n<p>For a more complete explanation, refer to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer">MDN</a> docs (or to my post referenced at the beginning of this answer).</p>\n<p>Basic example of a Reduce call:</p>\n<pre><code>let array = [1,2,3];\nconst initialMemo = [];\n\narray = array.reduce((memo, iteratee) =&gt; {\n    // if condition is our filter\n    if (iteratee &gt; 1) {\n        // what happens inside the filter is the map\n        memo.push(iteratee * 2); \n    }\n\n    // this return value will be passed in as the \'memo\' argument\n    // to the next call of this function, and this function will have\n    // every element passed into it at some point.\n    return memo; \n}, initialMemo)\n\nconsole.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]\n</code></pre>\n<p>more succinct version:</p>\n<pre><code>[1,2,3].reduce((memo, value) =&gt; value &gt; 1 ? memo.concat(value * 2) : memo, [])\n</code></pre>\n<p>Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as \'memo\' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the \'memo\' argument to the next function.</p>\n<p>Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:</p>\n<pre><code>[7,4,1,99,57,2,1,100].reduce((memo, val) =&gt; memo &gt; val ? memo : val)\n// ^this would return the largest number in the list.\n</code></pre>\n<p>An example of how to write your own reduce function (this often helps understanding functions like these, I find):</p>\n<pre><code>test_arr = [];\n\n// we accept an anonymous function, and an optional \'initial memo\' value.\ntest_arr.my_reducer = function(reduceFunc, initialMemo) {\n    // if we did not pass in a second argument, then our first memo value \n    // will be whatever is in index zero. (Otherwise, it will \n    // be that second argument.)\n    const initialMemoIsIndexZero = arguments.length &lt; 2;\n\n    // here we use that logic to set the memo value accordingly.\n    let memo = initialMemoIsIndexZero ? this[0] : initialMemo;\n\n    // here we use that same boolean to decide whether the first\n    // value we pass in as iteratee is either the first or second\n    // element\n    const initialIteratee = initialMemoIsIndexZero ? 1 : 0;\n\n    for (var i = initialIteratee; i &lt; this.length; i++) {\n        // memo is either the argument passed in above, or the \n        // first item in the list. initialIteratee is either the\n        // first item in the list, or the second item in the list.\n           memo = reduceFunc(memo, this[i]);\n        // or, more technically complete, give access to base array\n        // and index to the reducer as well:\n        // memo = reduceFunc(memo, this[i], i, this);\n    }\n\n    // after we\'ve compressed the array into a single value,\n    // we return it.\n    return memo;\n}\n</code></pre>\n<p>The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.</p>\n'}, {'answer_id': 58272005, 'author': 'Nicolas', 'author_id': 6325415, 'author_profile': 'https://Stackoverflow.com/users/6325415', 'pm_score': 0, 'selected': False, 'text': '<p>following statement cleans object using map function.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var arraytoclean = [{v:65, toberemoved:"gronf"}, {v:12, toberemoved:null}, {v:4}];\narraytoclean.map((x,i)=&gt;x.toberemoved=undefined);\nconsole.dir(arraytoclean);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 58880113, 'author': 'gkucmierz', 'author_id': 3573210, 'author_profile': 'https://Stackoverflow.com/users/3573210', 'pm_score': 0, 'selected': False, 'text': '<p>I just wrote array intersection that correctly handles also duplicates</p>\n\n<p><a href="https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0" rel="nofollow noreferrer">https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0</a></p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// array intersection that correctly handles also duplicates\r\n\r\nconst intersection = (a1, a2) =&gt; {\r\n  const cnt = new Map();\r\n  a2.map(el =&gt; cnt[el] = el in cnt ? cnt[el] + 1 : 1);\r\n  return a1.filter(el =&gt; el in cnt &amp;&amp; 0 &lt; cnt[el]--);\r\n};\r\n\r\nconst l = console.log;\r\nl(intersection(\'1234\'.split``, \'3456\'.split``)); // [ \'3\', \'4\' ]\r\nl(intersection(\'12344\'.split``, \'3456\'.split``)); // [ \'3\', \'4\' ]\r\nl(intersection(\'1234\'.split``, \'33456\'.split``)); // [ \'3\', \'4\' ]\r\nl(intersection(\'12334\'.split``, \'33456\'.split``)); // [ \'3\', \'3\', \'4\' ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 61328209, 'author': 'Rishab Surana', 'author_id': 6183464, 'author_profile': 'https://Stackoverflow.com/users/6183464', 'pm_score': 0, 'selected': False, 'text': '<p>First you can use map and with chaining you can use filter </p>\n\n<pre><code>state.map(item =&gt; {\n            if(item.id === action.item.id){   \n                    return {\n                        id : action.item.id,\n                        name : item.name,\n                        price: item.price,\n                        quantity : item.quantity-1\n                    }\n\n            }else{\n                return item;\n            }\n        }).filter(item =&gt; {\n            if(item.quantity &lt;= 0){\n                return false;\n            }else{\n                return true;\n            }\n        });\n</code></pre>\n'}, {'answer_id': 66282857, 'author': 'Senseful', 'author_id': 35690, 'author_profile': 'https://Stackoverflow.com/users/35690', 'pm_score': 1, 'selected': False, 'text': "<p>TLDR: Use <code>map</code> (returning <code>undefined</code> when needed) and <em>then</em> <code>filter</code>.</p>\n<hr />\n<p>First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function <code>flatMap</code> but then renamed it to <code>compactMap</code>.</p>\n<p>For example, if we don't have a <code>compactMap</code> function, we might end up with <code>computation</code> defined twice:</p>\n<pre><code>  let array = [1, 2, 3, 4, 5, 6, 7, 8];\n  let mapped = array\n  .filter(x =&gt; {\n    let computation = x / 2 + 1;\n    let isIncluded = computation % 2 === 0;\n    return isIncluded;\n  })\n  .map(x =&gt; {\n    let computation = x / 2 + 1;\n    return `${x} is included because ${computation} is even`\n  })\n\n  // Output: [2 is included because 2 is even, 6 is included because 4 is even]\n</code></pre>\n<p>Thus <code>compactMap</code> would be useful to reduce duplicate code.</p>\n<p>A really simple way to do something similar to <code>compactMap</code> is to:</p>\n<ol>\n<li>Map on real values or <code>undefined</code>.</li>\n<li>Filter out all the <code>undefined</code> values.</li>\n</ol>\n<p>This of course relies on you never needing to return undefined values as part of your original map function.</p>\n<p>Example:</p>\n<pre><code>  let array = [1, 2, 3, 4, 5, 6, 7, 8];\n  let mapped = array\n  .map(x =&gt; {\n    let computation = x / 2 + 1;\n    let isIncluded = computation % 2 === 0;\n    if (isIncluded) {\n      return `${x} is included because ${computation} is even`\n    } else {\n      return undefined\n    }\n  })\n  .filter(x =&gt; typeof x !== &quot;undefined&quot;)\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/9289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268/']