avatarRayRay

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5058

Abstract

figure><h2 id="60ef">How does the function work?</h2><p id="4a10">In our function, we define a parameter, <code>array</code>, which we expect to be an array. We check this in the <code>if</code> statement.</p><ul><li><code>!array</code>: We simply check if the array is <code>null</code> or <code>undefined</code></li><li><code>!Array.isArray(array)</code>: We use the array helper method to check if the value of <code>array</code> is, indeed, an array. If you put the <code>!</code> before it, we check if the output is <code>false</code> .</li><li><code>array.length === 0</code>: We use this to check if the array has a length of <code>0 </code>— this indicates an empty array</li></ul><p id="2367">If one of the conditions are met, we let the function return the array that has been given in the function.</p><p id="00c4">If the conditions aren’t met, it’ll put the array in the <code>new Set()</code>, and we turn it into an array by using the <code>...</code> spread syntax.</p><p id="a0c4">Finally, we need to call the function.</p><div id="3b37"><pre><span class="hljs-function"><span class="hljs-title">unDuplicateArraySingleValues</span><span class="hljs-params">(array)</span></span></pre></div><h2 id="489a">Test the function</h2><p id="505e">Check in the example below if everything works correctly.</p> <figure id="809b"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjwrj9&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjwrj9&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjwrj9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" allowfullscreen="" frameborder="0" height="500" width="1000"> </div> </div> </figure></iframe></div></div></figure><h1 id="4a45">2. Array With Duplicated Objects</h1><p id="3e30">Let’s define an example array of objects with duplicate information</p><div id="8911"><pre><span class="hljs-keyword">const</span> dupObjects = [ { <span class="hljs-attribute">id:</span><span class="hljs-string"> 1, name</span>: <span class="hljs-string">"a"</span>, <span class="hljs-attribute">value</span>: <span class="hljs-string">"c"</span> }, { <span class="hljs-attribute">id:</span><span class="hljs-string"> 2, name</span>: <span class="hljs-string">"b"</span>, <span class="hljs-attribute">value</span>: <span class="hljs-string">"d"</span> }, { <span class="hljs-attribute">id:</span><span class="hljs-string"> 2, name</span>: <span class="hljs-string">"c"</span>, <span class="hljs-attribute">value</span>: <span class="hljs-string">"e"</span> }, { <span class="hljs-attribute">id:</span><span class="hljs-string"> 3, name</span>: <span class="hljs-string">"d"</span>, <span class="hljs-attribute">value</span>: <span class="hljs-string">"c"</span> } ];</pre></div><p id="abf3">You can see there are a few property values that are duplicated.</p><p id="cb96">I think it sounds obvious that you don’t want any duplicated information in your array of objects.</p><h2 id="b44e">Create a function</h2><p id="117c">So we need a function that checks our array and, based on a given property, checks if there’s an other object that has a property with the same information.</p> <figure id="fd58"> <div> <div>

            <iframe class="gist-iframe" src="/gist/raymonschouwenaar/b1f50687289206f1287a5abfbcf71d20.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="0b1f">This <code>function</code> starts the same as in the previous example. So it’d be a good idea to make a new <code>function</code> for that. In this example, we keep it the same.</p><h2 id="d420">How does the function work?</h2><p id="68ea">In our <code>function</code>, we define a parameter, <code>array,</code> which we expect to be an array. We check this in the <code>if</code> statement.</p><ul><li><code>!array</code>: We simply check if the array is <code>null</code> or <code>undefined</code></li><li><code>!Array.isArray(array)</code>: We use the array helper method to check if the value of <code>array</code> is, indeed, an array. If you put the <code>!</code> before it, we check if the output is <code>false</code>.</li><li><code>array.length === 0</code>: We use this to check if the array has a length of <code>0 </code>— this indicates an empty array.</li><li><code>!property</code>: With this, we check if the property value is <code>false</code> — which means we check for <code>null</code>, <code>undefined</code>, or <code>0</code> . Because if any of these are the case, we can’t check for duplicate information in our objects.</li></ul><p id="81b3">Then we create a variable, <code>objectArrayKeys,</code> in which we store an arr

Options

ay of the values of the properties we’ve given in the <code>propertyName</code> parameter.</p><p id="90d7">In <code>uniqueKeys</code>, we remove duplicate values. But we make use of our previous function. This function returns a new array with only unique values.</p><p id="4124">At last, we return an array with only unique objects based on the <code>uniqueKeys</code> array.</p><p id="2f10">Finally, we need to call the function.</p><div id="dee9"><pre><span class="hljs-function"><span class="hljs-title">unDuplicateArrayObjects</span><span class="hljs-params">(dupObjects, <span class="hljs-string">"id"</span>)</span></span></pre></div><h2 id="f6c4">Test the function</h2><p id="2280">In the example below, check changing the property names in the function so we can verify everything works correctly.</p> <figure id="5115"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F44pdz&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F44pdz&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F44pdz%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" allowfullscreen="" frameborder="0" height="500" width="1000"> </div> </div> </figure></iframe></div></div></figure><h1 id="f5db">Conclusion</h1><p id="b52b">I hope you learned how to get rid of duplicated data in your array with single values or an array with objects.</p><p id="337c">I personally have googled this question thousands of times. That’s why I’ve written this tutorial for you.</p><figure id="7597"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*0fLVc6GjamTuPR79Cqce4Q.png"><figcaption></figcaption></figure><p id="6147">Hi, I’m<b> Ray</b> a Dutch 🇳🇱 JavaScript Developer and love to share my knowledge which I gained from being a Developer since 2009. I write stories about JavaScript, TypeScript, Angular, and anything related to life as a developer.</p><p id="ac9c">You can follow me on <a href="https://twitter.com/devbyrayray">Twitter</a> and <a href="https://www.instagram.com/devbyrayray/">Instagram</a> or <a href="https://buttondown.email/devbyrayray">subscribe to my newsletter</a> which I send when I post a new story.</p><p id="173c"><i>Happy Coding 🚀</i></p><h1 id="da03">Read More From Me</h1><div id="796a" class="link-block"> <a href="https://readmedium.com/build-fast-json-powered-forms-on-angular-with-ngx-formly-b7a00733e66e"> <div> <div> <h2>Build Fast, JSON-Powered Forms on Angular With NGX Formly</h2> <div><h3>Forms can be a nightmare — let’s make them better</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*eP7WbVOz5L0AsB_TeBJEZg.jpeg)"></div> </div> </div> </a> </div><div id="bbe3" class="link-block"> <a href="https://readmedium.com/you-dont-need-a-javascript-framework-df2a36c2dd0a"> <div> <div> <h2>You Don’t Need a JavaScript Framework</h2> <div><h3>Sometimes React, Angular, or Vue.js might be too much</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*AQJHMkYfMZ6H-_7S)"></div> </div> </div> </a> </div><div id="a286" class="link-block"> <a href="https://readmedium.com/2-ways-to-resolve-duplication-in-javascript-arrays-and-objects-e377e1bdc5e1"> <div> <div> <h2>2 Ways to Resolve Duplication in JavaScript Arrays and Objects</h2> <div><h3>Do you know how to deal with duplication?</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*DZg0829DQKwA3fxP)"></div> </div> </div> </a> </div><div id="09b8" class="link-block"> <a href="https://readmedium.com/7-steps-to-dockerize-your-angular-9-app-with-nginx-915f0f5acac"> <div> <div> <h2>7 Steps to Dockerize Your Angular 9 App With Nginx</h2> <div><h3>Set up your Angular 9 app in a Docker environment and deploy it in no time</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*ybCApnyoJFfRYkBEkGniUA.jpeg)"></div> </div> </div> </a> </div></article></body>

2 Ways to Resolve Duplication in JavaScript Arrays and Objects

Do you know how to deal with duplication?

Photo by Jaanus Jagomägi on Unsplash

In this article, I want to show you how simple it is to get rid of duplicated data. There are a few places duplicated data can appear for whatever reason.

There’s nothing more annoying than duplicated data in your JavaScript. So let’s get into a practical walk-through of how you can work against it.

I highly suggest not simply copying and pasting my code. Of course, you can — but please follow my explanation to understand how it works.

1. Array With Duplicated Strings or Numbers

const dupStrings = ['Angular', 'React', 'VueJS', 'Svelte', 'React']
const dupNumbers = [1,2,3,4,5,6,2,4,6,7,8,9,0]

The first array has some duplicated strings, and the other array has duplicated numbers in it.

To get rid of the duplicated data, we’re going to use Set. Set only accepts unique values.

"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.” — MDN Web Docs

console.log(new Set(dupStrings))
// Set(5) {"Angular", "React", "VueJS", "Svelte", ""}
console.log(new Set(dupNumbers))
// Set(10) {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}

When we put the arrays in a Set and output it to the console, you’ll see the duplicated values are removed from the array.

In the CodeSandbox below, you can see how it works.

But now, we turned it into a Set, and we need the cleaned array back so we can do our JavaScript magic further.

The easiest way to do this is by using the ... spread syntax inside the array brackets [...]. Let’s put that into a function so we can reuse it everywhere in our application.

Create a function

Now we need to create a function from it so we can reuse it on other places.

How does the function work?

In our function, we define a parameter, array, which we expect to be an array. We check this in the if statement.

  • !array: We simply check if the array is null or undefined
  • !Array.isArray(array): We use the array helper method to check if the value of array is, indeed, an array. If you put the ! before it, we check if the output is false .
  • array.length === 0: We use this to check if the array has a length of 0 — this indicates an empty array

If one of the conditions are met, we let the function return the array that has been given in the function.

If the conditions aren’t met, it’ll put the array in the new Set(), and we turn it into an array by using the ... spread syntax.

Finally, we need to call the function.

unDuplicateArraySingleValues(array)

Test the function

Check in the example below if everything works correctly.

2. Array With Duplicated Objects

Let’s define an example array of objects with duplicate information

const dupObjects = [
   { id: 1, name: "a", value: "c" },
   { id: 2, name: "b", value: "d" },
   { id: 2, name: "c", value: "e" },
   { id: 3, name: "d", value: "c" }
];

You can see there are a few property values that are duplicated.

I think it sounds obvious that you don’t want any duplicated information in your array of objects.

Create a function

So we need a function that checks our array and, based on a given property, checks if there’s an other object that has a property with the same information.

This function starts the same as in the previous example. So it’d be a good idea to make a new function for that. In this example, we keep it the same.

How does the function work?

In our function, we define a parameter, array, which we expect to be an array. We check this in the if statement.

  • !array: We simply check if the array is null or undefined
  • !Array.isArray(array): We use the array helper method to check if the value of array is, indeed, an array. If you put the ! before it, we check if the output is false.
  • array.length === 0: We use this to check if the array has a length of 0 — this indicates an empty array.
  • !property: With this, we check if the property value is false — which means we check for null, undefined, or 0 . Because if any of these are the case, we can’t check for duplicate information in our objects.

Then we create a variable, objectArrayKeys, in which we store an array of the values of the properties we’ve given in the propertyName parameter.

In uniqueKeys, we remove duplicate values. But we make use of our previous function. This function returns a new array with only unique values.

At last, we return an array with only unique objects based on the uniqueKeys array.

Finally, we need to call the function.

unDuplicateArrayObjects(dupObjects, "id")

Test the function

In the example below, check changing the property names in the function so we can verify everything works correctly.

Conclusion

I hope you learned how to get rid of duplicated data in your array with single values or an array with objects.

I personally have googled this question thousands of times. That’s why I’ve written this tutorial for you.

Hi, I’m Ray a Dutch 🇳🇱 JavaScript Developer and love to share my knowledge which I gained from being a Developer since 2009. I write stories about JavaScript, TypeScript, Angular, and anything related to life as a developer.

You can follow me on Twitter and Instagram or subscribe to my newsletter which I send when I post a new story.

Happy Coding 🚀

Read More From Me

Software Development
Coding
JavaScript
Programming
Tutorial
Recommended from ReadMedium