Array methods

Array methods

Array methods


In JavaScript, there exist a wide range of array methods. To give you more detailed and comprehensive information, we are going to split them into groups.

Add/Remove Methods

In chapter Arrays, we have already spoken about this group of methods. Among them are:

  • arr.push(...items)- helps to add items to the end;
  • arr.pop()- extracting an item from the end;
  • arr.shift()- extracting an item from the beginning;
  • arr.unshift(...items)- adding items to the beginning.

In this chapter, we will speak about several other methods.

Slice

arr.slice is a simple method, much simpler than arr.splice.

Its syntax is the following:

arr.slice([start], [end])

This method returns a new array copying to it all the items from index start to the end (but it doesn’t include the end). If both the start and the end are negative positions from the array, the end will be assumed.

It’s much like end method, but it makes subarrays instead of substrings.

Here is an example:

let arr = ["W", "3", "D", "o", "c", "s"];

console.log(arr.slice(1, 3)); // 3,D (copy from 1 to 3)

console.log(arr.slice(-2)); // c,s (copy from -2 till the end)

You can call it without arguments: str.slice will create a copy of arr.

Concat

The arr.concat method is used for creating a new array, including values from other arrays, as well as additional items. The syntax will look like this:

arr.concat(arg1, arg2...)

It will accept arguments at any quantity (arrays or values).

The result will be a new array with the items from arr, then arg1arg2, and more.

In case an argument argN represents an array, all its elements will be copied. In other cases, the argument will be copied.

For example:

let arr = ["a", "b"];

// create an array from: arr and ["c", "d"]

console.log(arr.concat(["c", "d"])); // a,b,c,d

// create an array from: arr and ["c", "d"] and [e,f]

console.log(arr.concat(["c",  "d"], ["e", "f"])); // a,b,c,d,e,f

// create an array from: arr and ["c", "d"], then add values e and f

console.log(arr.concat(["c", "d"], "e", "f")); // a,b,c,d,e,f

Iterate: forEach

The method arr.forEach allows running a function for each element of the array.

Here is the syntax:

arr.forEach(function (item, index, array) {
  // ... do something with item
});

In the following example, each element of the array is shown:

// for each element call alert
["dog", "cat", "mouse"].forEach(alert);

Searching in the array

In this part, we will cover the methods for searching in an array.

indexOf/lastIndexOf and includes

These methods have the same syntax doing the same as their string counterparts. The difference is that they operate on items, not on characters.

What they do:

  • arr.indexOf(item, from) searches for an item beginning from the index from and returns it to where it was found, otherwise -1.
  • arr.lastIndexOf(item, from) is similar, but searches from right to left.
  • arr.includes(item, from) searches for an item, beginning from the index from, and returns true, if it was found.

Let’s check out the following example:

let arr = [1, 0, false];

console.log(arr.indexOf(0)); // 1

console.log(arr.indexOf(false)); // 2

console.log(arr.indexOf(null)); // -1 

console.log(arr.includes(1)); // true

Take into account that these methods use comparison ===. Thus, when you look for false, it will find false and not zero.

Find and FindIndex

Let’s see that you have an array with objects and want to find an object with a specific condition. Then you need to use the arr.find(fn) method using this syntax:

let result = arr.find(function (item, index, array) {
  // if true is returned,the item is returned, and iteration is stopped
  // for falsy scenario returns undefined
});

The function will be called for the array elements, one after another, like this:

  • An item is an element.
  • The index will be its index.
  • The array will be the array itself.

In the event of returning true, the search will be stopped, and the item- returned.

For instance:

let animals = [{

    id: 1,

    name: "dog"

  },

  {

    id: 2,

    name: "cat"

  },

  {

    id: 3,

    name: "mouse"

  }

];

let animal = animals.find(item => item.id == 1);

console.log(animal.name); // dog

Filter

This method searches for the first element that makes the function return true.

In case there are many elements, you can use the arr.filter(fn) method. Its syntax looks like find, but the filter will return an array with all the matching elements:

let results = arr.filter(function (item, index, array) {
  // if true item is pushed to results and the iteration continues
  // returns empty array if nothing found
});

Here is an example:

let animals = [{

    id: 1,

    name: "dog"

  },

  {

    id: 2,

    name: "cat"

  },

  {

    id: 3,

    name: "mouse"

  }

];

// returns array of the first two animals

let someAnimals = animals.filter(item => item.id < 3);

console.log(someAnimals.length); // 2

Transforming an array

In this part, we will cover the methods targeted at transforming and reordering an array.

map

This method is one of the most useful and frequently used ones. Here is the syntax:

let result = arr.map(function (item, index, array) {
  // returns the new value instead of item
});

In this example, each element is transformed into its length:

let lengths = ["dog", "cat", "mouse"].map(item => item.length);

console.log(lengths); // 3,3,5

sort(fn)

This method is used for sorting the array in place, changing the element order.

Let’s have a look at the following example:

let arr = [1, 3, 25];

// the method reorders the content of arr

arr.sort();

console.log(arr); // 1, 25, 3

You will find something quite strange in the outcome. The order looked like 1, 25, 3

The reason is that the items are sorted as strings.

All the elements are converted to strings for comparisons. The lexicographic ordering is used for strings ( "3" > "25").

For using your sorting order, you need to supply a function as the argument of the arr.sort().

Here is an example:

function compareNumeric(a, b) {

  if (a > b) return 1;

  if (a == b) return 0;

  if (a < b) return -1;

}

let arr = [1, 3, 25];

arr.sort(compareNumeric);

console.log(arr); // 1, 3, 25

reverse

This method is targeted at reversing the order of the elements in arr.

For example:

let arr = ["a", "b", "c",  "d", "e"];

arr.reverse();

console.log(arr); // e,d,c,b,a

It can also return the array arr after reversing.

split and join

The str.split(delim) method is used for splitting the string into an array by the particular delimiter delim.

In the following example, it is split by a comma followed by space:

let animals = 'dog, cat, mouse';

let arr = animals.split(', ');

for (let animal of arr) {

  console.log(`A message to ${animal}.`); // A message to dog  (and other names)

}

By the way, this method has an alternative numeric argument that is a limit on the length of an array. In case it is provided, the extra elements will be ignored. Anyway, developers don’t use it often.

The example will look like this:

let arr = 'dog, cat, mouse, lion'.split(', ', 2);

console.log(arr); // dog, cat

If you want to reverse the split, call arr.join(glue). It will create an arr items string along with glue between them. Here is an example:

let animalsArr = ['dog', 'cat', 'mouse'];

let str = animalsArr.join(';'); // glue the array into a string using ; 

console.log(str); // dog;cat;mouse

reduce/reduceRight

For iterating over an array, you can apply forEachfor, or for..of.

In case you wish to iterate and return the data for each element, the map can be used.

The arr.reduce and arr.reduceRight methods do similar actions but are a bit more intricate. You can use it for calculating one value based on the array.

The syntax is as follows:

let value = arr.reduce(function (accumulator, item, index, array) {
  // ...
}, [initial]);

The arguments are:

  • the accumulator represents the result of the previous function call equaling initial the first time;
  • the item can be described as the current array item.
  • the index is its position.
  • the array is the array.

In this example, you can find a sum of an array in a single line:

let sumArr = [1, 2, 3, 4, 5];

let result = sumArr.reduce((sum, current) => sum + current, 0);

console.log(result); // 15

Array.isArray

Arrays are based on objects.

Hence, the typeof will not let you distinguish a plain object from an array:

console.log(typeof {}); // object

console.log(typeof []); // same

But developers use arrays so often that there exists a special method for doing it: Array.isArray(value). It returns true whenever the value is an array and false if not.

The example is the following:

console.log(Array.isArray({})); // false 

console.log(Array.isArray([])); // true

Reactions

Post a Comment

0 Comments

close