JavaScript: Arrays vs. Sets - The difference

The Set object type was introduced in the 2015 ECMAScript specification and is ready to be used in Node.js and most browsers.

Sets are a lot like Arrays, but a bit different. This article explores these differences and explains when one should be used over another. Let’s take a look.

Sets, the New Kid on the Block

Sets are a special object type available in ES6. You can create an empty set like this:

const characters = new Set()

Or, you can pass an iterable into the Set’s constructor to populate it. An iterable is just something that can be looped through, like an Array or a String.

const characters = new Set(['Rod', 'Todd', 'Sherri', 'Terri'])

Arrays, the Trusty Workhorse

Arrays are a major building block in most JavaScript applications, both old and new. If you have written JavaScript before, you are probably already familiar with them. You can create an array like this:

const characters = ['Rod', 'Todd', 'Sherri', 'Terri']

So What’s the Point?

These two data types are similar but are meant to do slightly different things. A set is designed to represent a collection of unique items whereas an array is a bit more general purpose.

A good example of something that could be represented as a Set would be the courses that a college student takes in a single semester. They can take one or more courses, but they can’t take the same course more than once in a semester.

const courses = new Set(['English', 'Science', 'Lego Robotics'])

On the other hand, a collection of Pokemon cards would not be a good use case for a Set because it could contain duplicates. In this case, an Array would be a better way to represent the data.

const cards = [
  'Machop',
  'Diglett',
  'Charmeleon',
  'Machop',
  'Squirtle'
]

Duplicates can be passed into a Set, but they won’t be preserved. Copy the following code into your browser console and see for yourself:

new Set([
  'Machop',
  'Diglett',
  'Charmeleon',
  'Machop',
  'Squirtle'
])
// Set(4) {"Machop", "Diglett", "Charmeleon", "Squirtle"}

The array passed into the set contained two Machops, but the set only retains one single copy. This behavior is subtle, but very useful.

How Can This Be Used?

Imagine that you are developing a blog and want to create a feature that allows visitors to search for posts that match one or more categories. Each category should only be applied once.

If you are using an Array to represent the list of active categories, you need to take care to avoid duplicates. This could be done by checking that the list does not already contain the category being added.

The indexOf or includes methods could be used to do this:

// If our list does not include the category
if (!list.includes(category)) {
  // Then add the new category to the list
  list.push(category)
}

I used to find myself writing this kind of code all the time, but Sets can be used to handle this problem automatically. You can simply use the add method and the Set will always remain unique.

// Just add the category to the list
// No need to perform any checks in advance!
list.add(category)

Converting a Set Back to an Array

We already saw that an Array can be converted to a Set by passing the Array into the Set’s constructor, but how can a Set be converted to an Array?

One option is to call the Array from method statically:

const set = new Set(['Casablanca', 'The Wizard of Oz', 'Jaws'])
const arr = Array.from(set)
console.log(arr)
// (3) ["Casablanca", "The Wizard of Oz", "Jaws"]

The ES6 spread operator is another option:

const set = new Set(['Casablanca', 'The Wizard of Oz', 'Jaws'])
const arr = [...set]
console.log(arr)
// (3) ["Casablanca", "The Wizard of Oz", "Jaws"]

Sets do not support functional programming methods like map, filter, and reduce so it’s often convenient to convert them to Arrays for processing.

Using Sets to Remove Duplicates From an Array

Even if you prefer to hold your data in Arrays, Sets can still be helpful. A handy trick for removing duplicates from an Array is to convert it to a Set and then convert it back.

const cards = [
  'Machop',
  'Diglett',
  'Charmeleon',
  'Machop',
  'Squirtle'
]
const uniqueCards = [...new Set(cards)]
console.log(uniqueCards)
// (4) ["Machop", "Diglett", "Charmeleon", "Squirtle"]

How Do Sets Know Which Values Are Unique?

So far we’ve seen how Sets only hold unique values, but how exactly are unique values determined? Let’s play around a bit and find out.

First, let’s add the value 3 to a set twice:

new Set([1, 2, 3, 4, 3])
// Set(4) {1, 2, 3, 4}

The second 3 disappears. This is consistent with what we’ve learned so far, but what if that last 3 is added as a string instead?

new Set([1, 2, 3, 4, '3'])
// Set(5) {1, 2, 3, 4, "3"}

Interesting. The Set considers 3 to be different than '3'. What if we add matching arrays to a set?

new Set([['Jesse Pinkman'], ['Jesse Pinkman']])
// Set(4) {['Jesse Pinkman'], ['Jesse Pinkman']}

In this case, the Set retains two Arrays that have the same contents… What about objects?

new Set([{name: 'Ron Burgundy'}, {name: 'Ron Burgundy'}])
// Set(2) {{name: 'Ron Burgundy'}, {name: 'Ron Burgundy'}}

Object literals with matching keys and values are considered to be different as well…

How Can All This Be Explained?

Sets use strict equality (===) to determine which values are unique. This explains why the set maintains a copy of both 3 (the number) and '3' (the string).

It also explains why Arrays and object literals that have the same contents are found to be unique. JavaScript compares objects by their reference, not their contents, and Arrays are just one particular kind of object.

Summary

Sets give JavaScript developers a new way to represent data. While Arraysremain the general-purpose workhorse of JavaScript applications, Setsare intended to represent a uniquecollection of values.

Converting between Sets and Arrays is easy. You can use a Set to ensure your data remains unique and then convert it to an Array to take advantage of functional methods like map, filter, and reduce.

Sets use _strict equality_to compare values and determine what is unique. Since JavaScript compares objects by reference, Arrays and object literals can be considered unique even when they contain the same contents.

This article focused on the conceptual side of Sets. You should now have a good idea of when a Set should be used, and when it would be better to stick to an Array.

Thank you !

#JavaScript #Nodejs #Programming #Coding

What is GEEK

Buddha Community

JavaScript: Arrays vs. Sets - The difference
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

Samanta  Moore

Samanta Moore

1624959720

Java Vs. JavaScript: Know the Difference

What a mess it could be to share the same name — especially if you are a programming language. Even if you are already over 20 years old, IT newbies periodically confuse you with your namesake. This happens all the time with Java and JavaScript, although they are not related at all! As someone on the internet said. They correlate in much the same way as a car and a carpet.

Why do these two languages have such similar names? How do they differ from each other, and what else do they have in common? This article will provide the answers to these questions.

In the Beginning, It Was Java

The Same Year, A Little Bit Later: Meet JavaScript!

Technical Differences Between Java and JavaScript

What Can You Build in Java and JavaScript?

#java #javascript #javascript-development #java-development #learn-to-code-java #learn-javascript #programming #java-vs-javascript

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

Mahipal Nehra

Mahipal Nehra

1584529038

Java vs. JavaScript: Know The Difference

Java vs. JavaScript

#java #javascript #Java vs. JavaScript #Java vs JavaScript #programming

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