As ES6 becomes more and more popular in web development, we’re likely going to be seeing – and writing – less code using other libraries. When it comes to WordPress, jQuery is still very common.

Personally, I don’t think there’s anything inherently wrong with using jQuery (though you might not need it) but I also think it’s important to keep your skills sharp and up to date with newer technologies.

Removing Duplicate Items with JavaScript: You Might Not Need jQuery

But learning to write ES6 code is not the purpose of this post, nor is how to achieve something using ES6.

Instead, it’s still about WordPress and jQuery. I’ll come back to ES6 at the end of the post. One of the things I’d love to cover, though, is how to remove duplicate items from a list with a common property.

Removing Duplicate Items (via jQuery)

More specifically, let’s assume that you have a list of items – perhaps it’s an ordered list, an ordered list, or even just a container with a set of children – and each child has a set of properties.

These properties could be class attributes, custom data properties, or something like that. For example, let’s say that we have an unordered list and each child item has a data-id property.

Further, let’s say that the list of items are constructed from the response of any given API where duplicates exist in the data. Sure, the server-side should handle this, but in the cases where it’s not done, it can still be done on the client-side.

Here’s the code for doing it with the commentary below it:

Note the following:

  • the function accepts a jQuery-wrapped list of items with children,
  • the children of a data-id element that’s used to determine if duplicate items exist,
  • we setup an array to determine if we’ve seen the item before,
  • if not, we add it to the list; otherwise, we remove it,
  • finally, we return the modified, more updated list.

And that’s nearly line-by-line what the code is doing.

Personally, I try not to use if/else statements within the context of a loop (or even outside of a loop), but there are times where it’s not a bad practice to do so, and this is one of them.

So What Was That About ES6?

Earlier, I mentioned that ES6 is on the rise and it’s something that we, as developers, should be learning. As I continue to do so, perhaps I’ll revisit this post and share how to achieve the same functionality using ES6 rather than jQuery to show how it can be done.

Removing Duplicate Items with JavaScript: ES6

Regardless, if you’re using WordPress and have been using jQuery for the years with which it’s been used, I urge you to step outside of the library and learn some of the newer features of the language.

Personally, I learn by doing, and though I had an initial propensity to default to jQuery, I optioned to go with ES6 in a project on which we’re currently working at the urging of a teammate.

Category:
Articles
Tags: