Debbie Clay

Debbie Clay

1553505115

How to Remove Duplicates from an Array in JavaScript?

#javascript #web-development

What is GEEK

Buddha Community

Edward Jackson

1553505302

Recently in one of my projects I had to remove duplicates from an array. Instead of looking up a npm package that could do it for me I chose to implement it myself. Here’s what I learned about this seemingly straightforward task.

The easiest way

The Set structure introduced in ES6 has made it unbelievably easy to remove duplicates from an array. It can be done with this one-liner:

function removeDuplicates<T>(collection: T[]) {
 return [...new Set(collection)];
}

The Set data structure takes an array of elements and removes all the duplicates from it. Set can handle both primitives and references, however it removes duplicates based on the === comparison so objects are only considered a duplicate if they reference the same place in memory.

Once Set has removed the duplicates, we can transform the Set back into an array by using the spread operator. The Set instance contains property [Symbol.iterator] which makes it possible for the object to be iterated and thus to transform it into an array.

A significant downside

The problem is that in a typical application we almost never check whether we deal with the same object based on its reference. Objects are mostly used to represent some entity and its properties. Those entities are usually stored in the database and have some kind of identifier that can be used to differentiate between them.

Let’s take a look at this scenario:

We have an array of objects that represent some entities, each having a unique property called id. After a call to an API was made three new objects need to be saved inside the array. We would like to not repeat the same entity twice so we call our previously defined function in order to remove the duplicated ones:

const state = [{ id: 1 }, { id: 2 }, { id: 3 }];

const incomingObjects = [{ id: 1 }, { id: 4 }, { id: 5 }];

removeDuplicates([...state, ...incomingObjects]);
// => [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 }, { id: 5 } ]

The function works as it is supposed to — it removes objects with the same reference — but in our case there were two objects that represented the same entity and they didn’t have the same reference. We would like to be able to choose what we want the differentiation to be based on. With this specific behavior in mind, let’s create a new function.

Removing duplicates on our own

As we have seen before, objects usually have some kind of an identifier field that can be used to distinguish the object. If an object doesn’t have such information stored in one of its properties then there really is no other way than to check the reference.

The basic idea for our function is as follows: a function provided as the second argument will return an identifier by which we will check for duplicates.

So let’s create a new removeDuplicates function:

type GetIdentifier<T> = (value: T) => any;
const defaultGetIdentifier: GetIdentifier<any> = (val) => val;

function removeDuplicates<T>(
 collection: T[],
 getIdentifier: GetIdentifier<T> = defaultGetIdentifier,
) {
 const identifierState: { [identifier: string]: boolean } = {};

 return collection.filter((value) => {
   const identifier = String(getIdentifier(value));

   if (identifierState[identifier]) {
     return false;
   }

   identifierState[identifier] = true;

   return true;
 });
}

Our function takes two arguments: collection which is an array of elements and, optionally, getIdentifier — a function that takes an element of the collection and returns its identifier.

Inside the identifierState object we keep the identifiers and, for each identifier, a boolean value that, when set to true, blocks all the future values with the same identifier to be saved in the resulting array.

identifier must be either an string or a number because we have to store it as a key inside the identifierState.

Finally, we use the Array.prototype.filter() method to make sure we return a new array. In the function provided to the method we first get the identifier of the current value and check whether it exists inside the state. If it does, we return false and therefore not include the value in the resulting array. If it doesn’t we know that the value, according to our identifier of choice, isn’t a duplicate, so we can set its identifier to true in the state and return true for it to be saved in the final array.

Let’s test it out

Primitive values

The second argument defaults to the defaultGetIdentifier function that works great with primitive values (because it returns the value itself as its identifier):

removeDuplicates([1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2]); // => [ 1, 2 ]

Objects

Coming back to the previous example:

const state = [{ id: 1 }, { id: 2 }, { id: 3 }];

const incomingObjects = [{ id: 1 }, { id: 4 }, { id: 5 }];

removeDuplicates([...state, ...incomingObjects], (val) => val.id);
// => [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 } ]

By mapping each object to its id property they can be correctly identified and thus objects with id equal to 1 are not repeated.

Trouble is now we won’t be able to compare objects by their reference. Should we not include any specific function as the second argument, the default getIdentifier will simply return the object itself. Then the following line will set identifier to a string: [object Object].

const identifier = String(getIdentifier(value));

And by this criterion all objects are the same and thus the resulting array will only contain the first one. Dealing with this is a topic for a different time, however.

Comparing the two solutions

Due to the differences in how our function work we can only compare their efficiency with arrays that contain primitive values.

In an array with a million numbers between 1 and 1000 generated randomly, the duplicates were removed in the following times:

solution with identifiers: 52.798ms
solution with set: 23.345ms

Keep in mind that you will probably never have to deal with arrays of this magnitude and for arrays with say 100 elements the difference is hardly noticeable.

Conclusion

The Set solution is both simpler and faster but falls short when it comes to differentiating objects based on anything other than reference. The second solution is way more flexible and can be applied to more complicated cases. The solution can handle essentially everything aside from comparing the references. It is always important to know the cases in which a given function is going to be used and prepare accordingly. Filtering objects by reference is very rare nowadays so I would just stick to the second solution.

Learn More

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

ES5 to ESNext — here’s every feature added to JavaScript since 2015

5 Javascript (ES6+) features that you should be using in 2019

Vuejs 2 Authentication Tutorial

JavaScript Functional Programming Explained: Fusion & Transduction

Learn JavaScript - JavaScript Course for Beginners

*Originally published by Maciej Cieślar at *https://blog.bitsrc.io

Lowa Alice

Lowa Alice

1624388400

JavaScript Arrays Tutorial. DO NOT MISS!!!

Learn JavaScript Arrays

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=oigfaZ5ApsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#arrays #javascript #javascript arrays #javascript arrays tutorial

Terry  Tremblay

Terry Tremblay

1602154740

Fill and Filter in Array in JavaScript

By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity.

Let’s see them together one by one with some amazing examples.

Array.fill():

The _fill()_ method changes all elements in an array to a static value, from a start index (default _0_) to an end index (default _array.length_). It returns the modified array.

In simple words, it’s gonna fill the elements of the array with whatever sets of params, you pass in it. Mostly we pass three params, each param stands with some meaning. The first param value: what value you want to fill, second value: start range of index(inclusive), and third value: end range of index(exclusive). Imagine you are going to apply this method on some date, so that how its gonna look like eg: array.fill(‘Some date’, start date, end date).

NOTE: Start range is inclusive and end range is exclusive.

Let’s understand this in the below example-

//declare array
var testArray = [2,4,6,8,10,12,14];

console.log(testArray.fill("A"));

When you run this code, you gonna see all the elements of testArray will be replaced by 'A' like [“A”,"A","A","A","A","A","A"].

#javascript-tips #array-methods #javascript-development #javascript #arrays

Cayla  Erdman

Cayla Erdman

1597470780

A quick guide to JavaScript Arrays

Introduction

Arrays are a structure common to all programming languages so knowing what they are and having a firm grasp on what you’re able to accomplish with Arrays will take you a long way in your journey as a software developer. The code examples I share in this post will be in JavaScript but the concepts are common among all languages. What you learn here can easily be translated to any other language you work with.

In this post I’ll be covering how to perform the create, read update and delete operations using arrays, some common functions that come with the Array prototype and also how to implement them.


What is an Array

Before we jump into the juicy bits of Arrays, lets quickly gloss over what they are. Arrays

  • are a fundamental data type in JavaScript
  • are an ordered collection of values called **elements **that are stored at and accessed via an index
  • are untyped, meaning that the elements of an array could be of different types. This allows us to create complex arrays such as an array of objects or even an array of arrays (multidimensional arrays)
  • can have elements that are constants or expressions
  • have a property called length that tells you the number of elements in the array
  • inherit properties from Array.prototype that includes a wide variety useful functions that can be called from arrays or array-like objects

CRUD operations using Arrays

If you’re not familiar with the term CRUD it stands for Create, Read, Update and Delete. In this section we’ll go through each one of these operations and cover different ways you can perform each one.

Creating Arrays

There are several ways you can create an Array but the most common ways are by using

  • the Array literal syntax
  • the Array constructor i.e. new Array()

Lets take a look at each one with examples

Array literal

The array literal is the most common way of creating an array. It uses the square brackets as a notion of a container followed by comma separated values inside the square brackets. The following examples show how to use the array literal syntax and how arrays are untyped i.e. can contain elements of different types.

Image for post

Examples of untyped arrays in JavaScript created with the array literal syntax.

Array constructor

Another way to create an array is through the Array constructor.

const myArray = new Array();

Using the Array constructor, as shown above, is the same as creating an array with the array literal syntax. i.e.

// The following two lines behave exactly the same way i.e. both create an empty arrays

const myArray = new Array();
const myOtherArray = [];

The array constructor, however, is able to receive arguments that allow it to behave in different ways depending on the number and type of arguments passed to it.

  • You can pass a single numeric argument which creates an array of the specified length. This option is mostly used when you know how many elements you’ll be placing in the array
const myArray = new Array(5);

Note: If you want to define the array with a specified size, as shown above, the argument passed must be a numeric value. Any other type would be considered as the first element that’ll be placed in the array.

  • Or you can pass two or more arguments or a non-numeric argument to place the values inside the array. This works the same way as shown in the array literal examples.

Image for post

Examples of arrays created by using the Array constructor in JavaScript

As stated earlier, these two ways are the most common ways of creating arrays that you’ll see and use 99% of the time. There are a few other ways but we won’t dive deep into how they work. They are

  • the spread operator const someArray = […someOtherArray]
  • the static method Array.of()
  • and the static method Array.from()

#javascript #web-development #javascript-tips #javascript-development #javascript-arrays #sql

Coy  Roberts

Coy Roberts

1600510680

Definitive Guide to Understand Javascript Array reduce()

Javascript array reduce() is an inbuilt method that is used to apply a function to each element in the array to reduce the array to a single value. The reduce() function executes the provided function for each value of an array from left-to-right. The return value of a function is stored in an accumulator.

Understanding Javascript array reduce()

JavaScript array reduce() is one of the pioneer function of functional programming. The reduce() method accepts two parameters, the total and the current value. If you want to add all the values of an array, then use the array reduce() function.

It is similar to both  Javascript map() and  Javascript filter() but, it differs in the callback arguments.

The callback now receives an accumulator (it accumulates all the return values. Its value is the accumulation of a previously returned accumulations), a current value, a current index, and finally, the whole array.

#javascript #javascript map #javascript filter #javascript array reduce

Javascript Array From Example | Array.prototype.from()

Javascript array from() is an inbuilt function that creates a new, shallow-copied array instance from an array-like object or iterable object.

The Array .from() lets you develop Arrays from the array-like objects (objects with a length property and indexed items) or  iterable objects ( objects where you can get its items, such as Map and  Set).

The Array from() function was introduced in ECMAScript 2015.

Javascript Array From Example

Array.from() method in Javascript is used to creates a new  array instance from a given array. If you pass a  string to the Array.from() function, then, in that case, every alphabet of the string is converted to an element of the new array instance. In the case of integer values, a new array instance simply takes the elements of the given Array.

The syntax of the Array.from() method is the following.

Syntax

Array.from(arrayLike[, mapFn[, thisArg]])

#javascript #ecmascript #javascript array from #array.prototype.from