Common Array Operations in JavaScript
Published: 2022-02-08 03:47:42

Array is one of the most common data structures in JavaScript. I will briefly record and summarize some of its operations here.

<!-- truncate -->

_This paper mainly includes:_

- Create an array
- Check if it's an array
- Array-like object and transform it to array
- Remove duplicate elements

<div className="google-adsense" data-slot="7086065790" />

## Create an array

Creating an array is a basic skill, which includes the following methods:

```js
const arr = [1, 2, 3];
const arr2 = new Array(3); // [,,]
const arr3 = new Array(2, 3); // [2, 3]
const arr4 = Array.of(2, 3); // [2, 3]
```

The one we usually use the most is array literals.

## Check if it's an array

The main way to tell if it's an array is:

```js
// one
Array.isArray(arr);
// two
arr instanceof Array;
// three
Object.prototype.toString.call(arr) === "[object Array]";
// four
arr.constructor === Array;
```

The first one is the most common way.

<div className="google-adsense" data-slot="8610900456" />

## Array-like object and transform it to array

We sometimes encounter arrays that are not real arrays, it is called array-like object. but we can transform it to array. eg: `arguments` or `HTMLCollection`.

```js
const eles = document.querySelectorAll("a"); // HTMLCollection
// one
Array.prototype.slice.call(eles);
// two
Array.from(eles);
// three
[...eles];
// four
function toArray(arrayLike) {
  let res = [];
  for (item of arrayLike) {
    res.push(item);
  }
  return res;
}
// five
Array.apply(null, eles);
// six
[].concat.apply([], eles);
```

## Remove duplicate elements

Array de-duplication essentially requires that two elements are compared for equality, and if they are, an element is discarded. For accurate judgment, we use `Object.is` for comparison.

### Set

The Set object lets you store unique values of any type, whether primitive values or object references.

```js
function unique(arr){
  return Array.from(new Set(arr)); // or [...new Set(arr)];
}
```

### reduce with includes

- **reduce** : executes a reducer function for array element, and returns the final accumulated value.
- **includes** : returns true if the value is present in the array.

```js
function unique(arr){
  return arr.reduce((acc, cur) => {
    if (!acc.includes(cur)) {
      acc.push(cur);
    }
    return acc;
  }, []);
}
```

<div className="google-adsense" data-slot="8494516233" />

## for loop with Map

- **Map** : The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

```js
function unique(arr) {
  const map = new Map();
  const ret = [];
  for (let i = 0; i < arr.length; i++) {
    if (!map.has(arr[i])) {
      map.set(arr[i], true);
      ret.push(arr[i]);
    }
  }
  return ret;
}
```

### filter with indexOf

- **indexOf** : returns the first index at which a given element can be found in the array, or -1 if it is not present.

```js
function unique(arr) {
  return arr.filter((item, index) => arr.indexOf(item) === index);
}
```


The original link: [https://www.jstyro.com/blog/common-array-operations-in-javascript](https://www.jstyro.com/blog/common-array-operations-in-javascript)