Understand and manipulate Javascript array

As you know, javascript is used quite a lot in web developer especially for front end modern web developer and not except me. I've known javascript for many years ago but recently I've focused on it. It's easy to use but if you want to master it you have understand deeply how it works. In this post we will look how to create, manipulate with array and understand some useful methods.

Create an Array

There are two ways to create array.

var countries = ['USA', 'France', 'England'];`  

and

var countries = new Array('USA', 'France', 'England');`  

But you should create array by the first approach. This's simple, new key work just make complicatedly.

Recognize an Array

How do you know an variable is an array? Let's try with 3 ways below:

Solution 1 (ECMAScript 5)

Array.isArray(countries);  

Solution 2

function isArray(x) {  
    return x.constructor.toString().indexOf('Array') > -1;
}
isArray(countries);  

Solution 3

countries instanceof Array  

Useful array methods

This is very interesting section. In my experience, I've used it a lot when working with array.
There is an important thing you need to understand about these method that is some methods will affect to current array and the others will not.

Methods affect to current array

push(): adds one or more elements to the end of an array and returns the new length of the array.

var countries = ['USA', 'France', 'England'];  
countries.push('Vietnam');  
console.log(countries);  
// ["USA", "France", "England", "Vietnam"]

// You also can add more than one items
countries.push('Italia', 'Mexico');  

We can use apply() method with push() to add an array into an array.

var countries = ['USA', 'France', 'England'];  
var asia = ['Vietnam', 'Thailand'];  
[].push.apply(countries , asia );
console.log(countries);  
// ["USA", "France", "England", "Vietnam", "Thailand"]

unshift(): adds one or more elements to the beginning of an array and returns the new length of the array.

pop(): removes the last element from an array and returns that element.

var countries = ['USA', 'France', 'England'];  
countries.pop();  
console.log(countries);  
// ["USA", "France"]

shift(): removes the *first * element from an array and returns that element. This method changes the length of the array.

reduce(): applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
Note: This function is very helpful in calculate sum of a numeric array.

var result = [1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {  
  return previousValue + currentValue;
});
console.log(result);  
// 10

reduceRight(): it works same to reduce() but from right-to-left.

splice(): changes the content of an array by removing existing elements and/or adding new elements. This method is very helpful in case we want to remove an existing item by index or also replace an item with a new item.

// remove item with index 2
var countries = ['USA', 'France', 'England'];  
countries.splice(1, 1);  
console.log(countries);  
// ["USA", "England"]

// add item after first item
countries.splice(1, 0, 'Vietnam');  
console.log(countries);  
// ["USA", "Vietnam", "England"]

sort(): with this method you can easy assume that it will sort the array. Yes it is. By default it will sort array according to string like "Alice" comes before "Join".

var countries = ['USA', 'France', 'England'];  
countries.sort();  
console.log(countries);  
// ["England", "France", "USA"]

Let's check with I have an array [2, 5, 1, 4], so how to sort it in descending order.

var numbers = [1, 5, 2, 4];  
numbers.sort(function(a, b) {  
  return b-a;
});
console.log(numbers);  
// [5, 4, 2, 1]

By passing a function to sort() will help us can sort an array with custom conditions.

Methods return a new array

Next, we will go through some methods which return a new array, they are also useful for copying or filtering an array.
filter(): creates a new array with all elements that pass the test implemented by the provided function. You can easy imagine the purpose of this function by its own name. There is a sample that I want to filter all countries have 'an' word inside their name.

var countries = ['USA', 'France', 'England'];  
var countriesWithAn = countries.filter(function(item, index, array){  
  return item.indexOf('an') > -1;
});

console.log(countriesWithAn);  
// ["France", "England"]
console.log(countries);  
// ["USA", "France", "England"]

map(): creates a new array with the results of calling a provided function on every element in this array. This method is very helpful in case we want to create a new array base on an existing array. For example, I want to create new countries array with country code base on existing array ['USA-US', 'France-FR', 'England-EN'].

var countries = ['USA-US', 'France-FR', 'England-EN'];  
var countriesCodes = countries.map(function(item, index, array){  
  var country = item.split('-');
  return {
    countryName: country[0],
    countryCode: country[1]
  };
});
console.log(countriesCodes);  
/*
[{
  countryCode: "US",
  countryName: "USA"
}, {
  countryCode: "FR",
  countryName: "France"
}, {
  countryCode: "EN",
  countryName: "England"
}]
*/

slice(): returns a shallow copy of a portion of an array into a new array object. By this example code below, I try to copy array start from position 1 to 3.

var countries = ['USA-US', 'France-FR', 'England-EN', 'Vietnam-VN'];  
var copied = countries.slice(1, 3);  
console.log(copied);  
// ["France-FR", "England-EN"]

Or you can copy exactly an array:

var newArray = countries.slice();  

concat(): returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments. This method is useful in case we want to append an array or just values to an array.

var countries = ['USA-US', 'France-FR', 'England-EN'];  
var concatArray = countries.concat(1, 2, [5,6,7])  
console.log(concatArray);  
// ["USA-US", "France-FR", "England-EN", 1, 2, 5, 6, 7]

Methods return a bool

every(): There is a situation that I want to know all member in the array [2, 4, 7, 9] are greater than 1 or not. Let's see how we can check.

var list = [2, 4, 7, 9];  
var isAllGreaterThanOne = list.every(function(item, index, array) {  
  return item > 1;
});
console.log(isAllGreaterThanOne);  
// true

some(): This method is opposite to every(). It will return true if there is at least one item in array pass the condition. For example, I want to know at least an item in array less than 5.

var list = [2, 4, 7, 9];  
var isHasOneArrayLessThanFive = list.some(function(item, index, array) {  
  return item < 5;
});
console.log(isHasOneArrayLessThanFive);  
// true

Others and ECMAScript 2015

We have some new methods from ECMAScript 2015 like find() and findIndex(). In the past we will have to use another solution to find an item in array (using filter method), now it's more easier.

var countries = [{  
     countryCode: "US",
     countryName: "USA"
  }, {
     countryCode: "FR",
     countryName: "France"
  }, {
     countryCode: "EN",
     countryName: "England"
}];
var usa = countries.find(function(item, index, array) {  
  return item.countryCode === 'US'
});

var usaIndex = countries.findIndex(function(item, index, array) {  
  return item.countryCode === 'US'
});
console.log(usa);  
console.log(usaIndex);  
// {
//    countryCode: "US",
//    countryName: "USA"
// }
// 0

Note: They are not supported by Internet Explore and Opera!
indexOf(): returns the first index at which a given element can be found in the array, or -1 if it is not present. We can use it to check an array contains a specific item or not.

var list = [1, 2, 3, 4];  
var indexFound = list.indexOf(2);  
console.log(indexFound);  
// 1

join(): joins all elements of an array into a string.

var countries = ['USA', 'France', 'England'];  
var countriesInString = countries.join(' - ');  
console.log(countriesInString );  
// "USA - France - England"

Conclusion

All methods that I've listed above are very useful when working with Javascript. I separate three parts that will help you easy to understand the purpose of each method. Because in the past I used to wonder whether these method returns a new array or modify its own.
Hopefully this article will help you confident to work on array in Javascript.

Nguyen Tran

I'm Nguyen, a full stack web passion for frontend and love Angular.

Subscribe to Nguyen Tran

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!