Stamp here


What are Array and Set

Everyone who programs in JavaScript should be familiar with Array. In general, an array represents a type of structure (number,object, etc.) stored in contiguous space. For example: [1, 2, 3, 4, 5]

Set, on the other hand, is more of an abstract data type. It contains only different elements/objects and does not require continuous allocation of storage space. For example: {1, 2, 3}

The biggest difference is that the elements in Array are repeatable, while the elements in Set are not. In addition, Array is considered a collection of indexes, while Set is a collection of keys.

An index set is a collection of data structure keys sorted by index values using keys to access elements in the same order as they were inserted.

Easy, right? Now, one might ask, why compare the two when they are so different?

When programming, we can use Array or Set to store the same data Set. But depending on usage, we should choose the right data structure to help provide the best solution. In order to achieve this goal, we first need to understand what they are, what characteristics and capabilities. Now that we’ve looked at these two data structures in the previous article, let’s look at how they are built.

How to build

Array

To declare an array in JS, you can use the literal syntax:

var arr = []; / / an empty array
var arr = [1.2.3]; // Array of elements 1,2, and 3
Copy the code

Or use the constructor:

var arr = new Array(a);/ / an empty array
var arr = new Array(1.2.3);// Array of elements 1,2, and 3
Copy the code

And even this cooler way:

var arr = Array.from("123"); / / / "1", "2", "3"]
Copy the code

Note: One piece of advice — try not to use new Array() except when absolutely necessary, for the following reasons:

  • new Array()Performance than[]Much slower
  • []Save more input time
  • You might make some classic mistakes like:
var arr1 = new Array(10); // The length is 10, and each element is undefined
var arr2 = [10]; // arr2[0] = 10 and arr2.length = 1;
var arr3 = new Array(1.2.3); / / [1, 2, 3]
var arr4 = [1.2.3];/ / [1, 2, 3]
Copy the code

So try to keep it simple

Set

There is no easy way to initialize a Set using a built-in constructor.

Set([iterable])

To create a Set, use the new method, for example:

var emptySet = new Set(a);var exampleSet = new Set([1.2.3]);
Copy the code

The following methods cannot be used:

new Set(1);
Copy the code

The Set takes a traversable object as its input parameter and generates objects from the traversable elements in turn as elements in the Set. Therefore, we can create sets with arrays as arguments — but only the non-repeating elements of the array are included in the Set. As mentioned above, the elements in the Set cannot be repeated.

Of course, we can also restore a Set to an Array using array.from () :

var set = new Set([1.2.3]); / / {1, 2, 3}
var arr = Array.from(set);/ / [1, 2, 3]
Copy the code

Now that we know how to build these two data structures, let’s compare the most basic methods Array/Set provides.

Access to the elements

  • First, Set does not support random access to elements by index, as Array does
console.log(set[0]); //undefined
console.log(arr[0]); / / 1
Copy the code
  • More importantly, because the data in an Array is stored in contiguous space, the CPU can access the data faster through preprocessing operations. Therefore, accessing elements in an Array (in order, for example, through a for loop) is usually faster and more efficient compared to other types of abstract data types.
  • The syntax for determining whether an element is in a Set is cleaner than whether it is in an Array. Set:Set.prototype.has(value). Array:Array.prototype.indexOf(value).
console.log(set.has(0)); // boolean - false
console.log(arr.indexOf(0)); // -1
console.log(set.has(1)); //true
console.log(arr.indexOf(1)); / / 0
Copy the code

This means that in an Array, we need to create additional conditions to check whether the element is in the Array:

var isExist = arr.indexOf(1)! = =- 1;
Copy the code

Note: ES6 provides a array.prototype.includes () method similar to set.prototype.has () to determine if an element is in an Array, but this method is not widely supported by browsers — IE, for example..

Insert elements

Array

  • Inserting elements into an array can be done with O(1) timeArray.prototype.push()Method completes quickly – the element will be inserted at the end of the array.
arr.push(4); / / [1, 2, 3, 4]
Copy the code
  • Or you can use O(n)Array.prototype.unshift()Method implementation – The element is inserted into the head of the array.
arr.unshift(3); / /,1,2,3 [3]
arr.unshift(5.6); / /,6,3,1,2,3 [5]
Copy the code

Set

  • There is only one method to insert elements into a SetSet.prototype.add(). Because Set needs to maintain its element non-repeatable nature, it is called every timeadd()Methods, sets need to facilitate all elements to ensure that there are no duplicate elements, in generaladd()The time complexity of the method should be O(n). However, the internal implementation of Set using hash table, so it can achieve O(1) time complexity.
set.add(3); / / {1, 2, 3}
set.add(4); / / {1, 2, 3, 4}
Copy the code

Remove elements

Array

  • One of the things that makes arrays so popular is that they provide many different ways to delete elements, such as:
var arr = [5.6.1.2.3.4]
Copy the code

Pop () — Removes and returns the last element, time complexity O(1)

arr.pop();/ / return 4,,6,1,2,3 [5]
Copy the code

Shift () — Remove and return the first element, time complexity O(n)

arr.shift(); //return 5; ,1,2,3 [6]
Copy the code

Splice (index, delectCount) – Deletes delectCount elements starting with index. Time is order n.

arr.splice(0.1); / / [1, 2, 3]
Copy the code

Set

var set = new Set([1.2.3.4]);
Copy the code

Delete (Element) — Deletes the specified element

set.delete(4); / / {1, 2, 3}
Copy the code

Clear () — Clears all elements in the Set

set.clear(); / / {}
Copy the code

Array does not provide a native way to delete specified elements. Instead, we need to find the element’s subscript using splice(), whereas sets can be deleted directly using delete().

In addition, Array provides more useful native methods (reduce(),map(),sort(), etc.) than Set provides basic methods for manipulating data,so some might wonder why we prefer Set to Array.

Application scenarios of Array and Set

  • First, a Set is a different data structure from Array. Rather than replacing Array entirely, it provides additional data types to perform some of the functionality that Array lacks.
  • Since a Set contains only different elements, it is better to use a Set if we only want to store different elements.
  • You can use some of the native methods of Set to easily complete array deduplication, find the array of common elements and different elements operations. The Set ofdelete()Method to make finding the intersection/union of two sets easier than finding the intersection/union of two arrays.
  • Arrays are suitable for scenarios where you want to keep duplicate elements, possibly with a lot of modification (add and delete), or where you want quick access to elements through indexes. (Imagine a binary search of a Set — how do I get the middle element of the Set?)

conclusion

In summary, as far as I’m concerned, Set doesn’t have a significant advantage over Array, except in certain scenarios, such as when we want to maintain non-repetitive data at minimal cost, or when we’re working with a large number of different data sets and only need to use the most basic Set operations without directly accessing elements.

Otherwise, Array is usually a better choice. Because it is less CPU effort to retrieve elements when needed.

Welcome to the discussion.

Links to other information:

  • Array – MDN – Mozilla
  • Set – MDN – Mozilla
  • Ruan Yifeng – Introduction to ES6