Skip to main content

Common Array Operations in JavaScript

ยท 3 min read

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

This paper mainly includes:

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

Create an arrayโ€‹

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

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:

// 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.

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.

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.

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.
function unique(arr){
return arr.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
}

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.
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.
function unique(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}