{"id":223,"date":"2014-08-18T07:00:00","date_gmt":"2014-08-18T07:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/2014\/08\/18\/deleting-elements-from-an-javascript-array-and-closing-up-the-gaps\/"},"modified":"2014-08-18T07:00:00","modified_gmt":"2014-08-18T07:00:00","slug":"deleting-elements-from-an-javascript-array-and-closing-up-the-gaps","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20140818-00\/?p=223","title":{"rendered":"Deleting elements from an JavaScript array and closing up the gaps"},"content":{"rendered":"<p>\nToday&#8217;s Little Program is an exercise that solves the following problem:\n<\/p>\n<blockquote CLASS=\"m\">\n<p>\nGiven a JavaScript array <code>a<\/code>\nand an unsorted array <code>indices<\/code>\n(possibly containing duplicates),\ncalculate the result of deleting all of the elements from the original\narray as specified by the indices.\nFor example, suppose\n<code>a = [\"alice\", \"bob\", \"charles\", \"david\", \"eve\"]<\/code>\nand\n<code>indices = [2, 4, 2, 0]<\/code>.\n<\/p>\n<table BORDER=\"0\">\n<\/tr>\n<tr>\n<td><code>a[0]&nbsp;<\/td>\n<td><code>= \"alice\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a[1]&nbsp;<\/td>\n<td><code>= \"bob\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a[2]&nbsp;<\/td>\n<td><code>= \"charles\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a[3]&nbsp;<\/td>\n<td><code>= \"david\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a[4]&nbsp;<\/td>\n<td><code>= \"eve\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a.length<\/td>\n<td><code>= 5;<code><\/td>\n<\/tr>\n<\/table>\n<p>\nThe indices specify that elements 2 (charles), 4 (eve),\n2 (charles again, redundant), and 0 (alice) should be\ndeleted from the array,\nleaving bob and david.\n<\/p>\n<\/blockquote>\n<p>\nNow, if you had to delete only one element from the array,\nit is pretty simple:\n<\/p>\n<pre>\na.splice(n, 1);\n<\/pre>\n<p>\nThe trick with removing multiple elements is\nthat deleting one element shifts the indices,\nwhich can throw off future calculations.\nOne solution is to remove the highest-indexed element first;\nin other words, operate on the indices in reverse sorted order.\n<\/p>\n<pre>\nindices.sort().reverse().forEach(function(n) { a.splice(n, 1); });\n<\/pre>\n<p>\nThis technique does still suffer from the problem that if\nthere are duplicates in the indices,\nextraneous elements get deleted by mistake.\n<\/p>\n<p>\nAnother approach is to reinterpret the problem by focusing not on\nthe deletion but on the survivors:\nProduce the array consisting of elements whose indices are not\nin the list of indices to be deleted.\n<\/p>\n<pre>\na = a.filter(function(e, i) { return indices.indexOf(i) &gt;= 0; });\n<\/pre>\n<p>\nThe above approach works well if the list of indices to be deleted\nis short, but it gets quite expensive if the list is long.\n<\/p>\n<p>\nMy approach is to use the fact that JavaScript arrays can be sparse.\nThis is a side effect of the fact that JavaScript array indices\nare actually object properties;\nthe only thing that makes arrays different from generic objects in\na language-theoretic sense is\nthe magic <code>length<\/code> property:\n<\/p>\n<ul>\n<li>If a new property is added, and the property name\n    is the stringification of a whole number,\n    then the <code>length<\/code> is updated to the numeric\n    value of the added property name, plus 1.<\/p>\n<li>If the <code>length<\/code> property is modified programmatically,\n    the new value must be a whole number,\n    and\n    all properties which are the stringification of a whole number\n    greater than or equal to the new <code>length<\/code>\n    are deleted.\n<\/ul>\n<p>\n(See\n<a HREF=\"http:\/\/www.ecma-international.org\/publications\/standards\/Ecma-262.htm\">\nECMA-262<\/a>\nsections\n<a HREF=\"http:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-15.4\">\n15.4<\/a>,\n<a HREF=\"http:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-15.4.5.1\">\n15.4.5.1<\/a>,\nand\n<a HREF=\"http:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-15.4.5.2\">\n15.4.5.2<\/a>\nfor nitpicky details.)\n<\/p>\n<p>\nThe first step, then, is to delete all the indices that need to be deleted.\n<\/p>\n<pre>\nindices.forEach(function(n) { delete a[n]; });\n<\/pre>\n<p>\nWhen applied to our sample data, this leaves\n<\/p>\n<table BORDER=\"0\">\n<\/tr>\n<tr>\n<td><code>a[1]&nbsp;<\/td>\n<td><code>= \"bob\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a[3]&nbsp;<\/td>\n<td><code>= \"david\";<code><\/td>\n<\/tr>\n<tr>\n<td><code>a.length<\/td>\n<td><code>= 5;<code><\/td>\n<\/tr>\n<\/table>\n<p>\nwhich\ngets printed in a rather goofy way:\n<code>a = [, \"bob\", , \"dave\", ]<\/code>.\n<\/p>\n<p>\nThe next step is to close up the gaps.\nWe take advantage of the fact that the <code>Array<\/code>\nenumeration methods operate on indices 0 through <code>length - 1<\/code>\nand that they <i>skip missing elements<\/i>.\nTherefore, I can simply apply a dummy filter:\n<\/p>\n<pre>\na = a.filter(function() { return true; });\n<\/pre>\n<p>\n<b>Exercise<\/b>:\nWhat is the difference (aside from performance) between\n<code>a.push(1);<\/code> and <code>a = a.concat(1);<\/code>?\nHow is this question relevant to today's exercise?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today&#8217;s Little Program is an exercise that solves the following problem: Given a JavaScript array a and an unsorted array indices (possibly containing duplicates), calculate the result of deleting all of the elements from the original array as specified by the indices. For example, suppose a = [&#8220;alice&#8221;, &#8220;bob&#8221;, &#8220;charles&#8221;, &#8220;david&#8221;, &#8220;eve&#8221;] and indices = [&hellip;]<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-223","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Today&#8217;s Little Program is an exercise that solves the following problem: Given a JavaScript array a and an unsorted array indices (possibly containing duplicates), calculate the result of deleting all of the elements from the original array as specified by the indices. For example, suppose a = [&#8220;alice&#8221;, &#8220;bob&#8221;, &#8220;charles&#8221;, &#8220;david&#8221;, &#8220;eve&#8221;] and indices = [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/223","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=223"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/223\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=223"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=223"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=223"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}