Arrays are one of the most common data structures there is, and you need to be absolutely confident using it. Here I will list top 8 array manipulation snippets in JavaScript, including array length, replacing elements, sorting, and many others.
1. Array length
Most of you know that you can get the length of an array like this:
const a = [1, 2, 3];
console.log(a.length); // 3
The fun thing is, that you can modify the length manually. This is what I am talking about:
const a = [1, 2, 3];
a.length = 2;
a.forEach(i => console.log(i)); // 1 2
And even create new arrays with specified lengths:
const a = [];
a.length = 100;
console.log(a) // [undefined, undefined, undefined ...
This is not a very good practice, but worth knowing nonetheless.
2. Replacing elements of array
There are a few approaches to this. If you need to replace elements at specified indexes, use splice
:
const a = [1, 2, 3];
a.splice(2, 1, 4); // change 1 element at index 2 to 4
console.log(a); // [1, 2, 4]
a.splice(0, 2, 5, 6) // change 2 elements at index 0 to 5 and 6
console.log(a); // [5, 6, 4]
If you need to replace items based on their content or it is imperative that you create a new array, use map
:
const a = [1, 2, 3, 4, 5, 6];
// Now square all odd numbers
const b = a.map(item => item % 2 == 0 ? item : item*item);
console.log(b); // [1, 2, 9, 4, 25, 6];
map
accepts a function as its argument. It will call this function once for every element of the array and make a new array of items that functions return.
3. Filtering the array
In some cases you need to get rid of certain elements in an array, creating a new one. In this case, use the awesome new filter
method introduced in ES6:
const a = [1, 2, 3, 4, 5, 6, 7];
// Filter out all odd numbers
const b = a.filter(item => item % 2 == 0);
console.log(b); // [2, 4, 6];
filter
works very similar to map
. You supply it with a function, and filter
will call it on every element of the array. Function must return true if you want to include this particular element in the new array, and false otherwise.
4. Merging arrays
If you want to combine multiple arrays into one, there are 2 approaches. Pre-ES6 JS provided the concat
function:
const a = [1, 2, 3];
const b = [4, 5, 6];
console.log(a.concat(b)); // [1, 2, 3, 4, 5, 6]
However, there is a more convenient method, thanks to the spread operator introduced in ES6:
const a = [1, 2, 3];
const b = [4, 5, 6];
console.log([...a, ...b]);
5. Duplicating arrays
Being busy coding, it is easy to forget that variables do not store the array, but merely a reference. Here is what I mean:
const a = [1, 2, 3];
const b = a;
b[0] = 4;
b[1] = 2;
b[2] = 0;
console.log(a); // [4, 2, 0]
Since b
holds the reference to a
, any changes to b
are also changes to a
. To resolve this pre-ES6, use the slice
function:
const a = [1, 2, 3];
const b = a.slice(0);
b[1] = 5;
console.log(a); // [1, 2, 3];
console.log(b); // [5, 2, 3];
If you are in a ES6+ friendly environment, you can also use the spread operator:
const a = [1, 2, 3];
const b = [...a];
b[1] = 5;
console.log(a); // [1, 2, 3];
console.log(b); // [5, 2, 3];
6. Removing duplicates from arrays
There are 3 approaches to removing duplicates from arrays. The first 2 are pre-ES6, and the 3rd one is using new features.
Using reduce
. You can use the reduce
function to remove all the duplicates from the array. It is a bit tricky, however. reduce
will accept a function and pass 2 arguments in it: the current value from the array, and the accumulator. The accumulator stays the same across items and is ultimately returned:
const a = [1, 1, 2, 3, 1, 5, 9, 4, 2];
const b = a.reduce(
(acc, item) =>
acc.indexOf(item) == -1 ? acc : [...acc, item],
[] // initial accumulator
);
console.log(b); // [1, 2, 3, 5, 9, 4]
Using filter. Another function that can help you remove duplicates from an array in JavaScript is filter
, which we covered earlier:
const a = [1, 1, 2, 3, 1, 5, 9, 4, 2];
const b = a.filter((item, index) => a.indexOf(item) == index);
console.log(b); // [1, 2, 3, 5, 9, 4]
Using set. Lastly, you can use the Set
, a new data structure introduced in ES6, and the spread operator:
const a = [1, 1, 2, 3, 1, 5, 9, 4, 2];
const b = [...(new Set(a))];
console.log(b); // [1, 2, 3, 5, 9, 4]
7. Converting arrays
Sometimes you have to convert some other data structure like a set or a string into an array. In this case, use the Array.from
function:
const str = 'abacaba';
const st = new Set(1, 2, 3);
console.log(Array.from(str)); // ['a', 'b', 'a' ...
console.log(Array.from(st)); // [1, 2, 3]
8. Iterating over arrays
There are a couple of handy methods for iterating over arrays. The simplest one that is suitable for all JS versions is a regular for loop:
const a = [1, 2, 3];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
}
// 1 2 3
With newer, ES6-compliant JS, you get the foreach loop as well:
for (const i of a) {
console.log(i);
}
// 1 2 3
And, lastly, the forEach
function:
a.forEach(i => console.log(i)); // 1 2 3
forEach
works much like map
, filter
, and reduce
: it will call the function once per every item, but will not return anything.
Closing notes
Thank you for reading, I hope you liked my article. Stay subscribed for more interesting material on JavaScript and Software Development!