JavaScript Arrays 🙏🏻 – Most useful functions for developers
Tags: javascript, beginners, tutorial
Published: 2020-06-02 10:08:24


_Originally published on [webdeasy.de](https://webdeasy.de/en/useful-javascript-array-functions/)!_

JavaScript arrays have always offered many great features. Especially with the introduction of ES6 and the Arrow Functions, other useful features have been added. I have compiled a list of useful JavaScript array functions and show you with examples what they can do.

JavaScript arrays are already a great thing. In addition to the many possibilities, you have another decisive advantage over arrays in other programming languages: __They have much more useful functions.__

Besides all the array standard functions, like `push()` and `pop()`, there are also many useful functions that allow to reach the desired goal with little code. Don’t you think so? Well, just wait and see!

I have added corresponding examples to all functions.


#What are JavaScript arrays anyway?
JavaScript arrays are to be understood as arrays in most other known programming languages. They allow you to store several values in a single variable, to query, delete or modify them there.

In hardly any program it is possible to imagine a program without arrays, and arrays are also an important component when programming JavaScript.

No matter if you program in Vanilla JS, Vue.js, React.js or Node.js, you will encounter JavaScript arrays everywhere.

Besides the standard functions, like adding or deleting single elements in an array, JavaScript offers many useful functions to perform operations on and with arrays.

If you want to know more about the basics, you can take a look at [this article](https://javascript.info/array). But we’ll go straight to the cool and useful features.


#1. Array.map() – Perform tasks WITHOUT loop
This function performs a desired operation on each element in the array. This returns a new array with the changed entries. This saves us the programming of a loop and in the best case we can implement our function as a one-liner.

For clarity we have an element with fruits, which we want to change.
```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
const fruitsLongerSix = fruits.map(fruit => 'Fruit: ' + fruit);
console.log(fruitsLongerSix); // Output: ["Fruit: banana", "Fruit: apple", "Fruit: avocado", "Fruit: cherry", "Fruit: grapefruit", "Fruit: melon"]
```

If our statement becomes more complicated, we can also outsource the callback in a separate function. It would look like this:

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
const fruitsLongerSix = fruits.map(addPrefix);
function addPrefix(entry) {
    return 'Fruit: ' + entry;
}
console.log(fruitsLongerSix); // Output: ["Fruit: banana", "Fruit: apple", "Fruit: avocado", "Fruit: cherry", "Fruit: grapefruit", "Fruit: melon"]
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)


#2. Array.filter() – Sort out elements WITHOUT loop
This function creates a new array with all elements that pass the implemented test. This means we can filter our array, just as we like. This is a simple and clean method to filter list entries.

We have here again our array with fruits and only need entries with an “o” in the name. With a single line we can implement this function.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
let filtered = fruits.filter(fruit => fruit.indexOf('o') > -1);
console.log(filtered); // Output: ["avocado", "melon"]
```

If the filtering becomes a bit more complex, we can again outsource the callback of the `filter()` function to an extra function, as in the following example:

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
let filtered = fruits.filter(getO);
function getO(entry) {
    return entry.indexOf('o') > -1;
}
console.log(filtered); // Output: ["avocado", "melon"]
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)


#3. Array.forEach() – We no longer need a for loop
This function can replace our `for` loop. With less code we can iterate over every element of an array. In principle, it works like the `map()` function, except that no new array is created here.

This is what a normal loop looks like. Much simpler and clearer than a `for` loop, right?

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
fruits.forEach((fruit) => {
    console.log(fruit);
});
// Output:
// banana
// apple
// avocado
// cherry
// grapefruit
// melon
```

Sometimes we need an additional index, or as I like to call it “counter”. This can also be realized with this function. For this purpose we specify an additional variable `index` in the function header.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
fruits.forEach((fruit, index) => {
    console.log(index, fruit);
});
// Output:
// 0 "banana"
// 1 "apple"
// 2 "avocado"
// 3 "cherry"
// 4 "grapefruit"
// 5 "melon"
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)


#4. Array.indexOf() – Where is my element?
The function returns us the index – i.e. the location – of an element in an array. So we can also use it to check if a certain element is in the array.

If we get the result of the function, we get the respective index back. If an element is not present, we get `-1` back.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
console.log(fruits.indexOf('banana')); // Output: 0 (it's the first index)
console.log(fruits.indexOf('cherry')); // Output: 3
onsole.log(fruits.indexOf('toast')); // Output: -1
```

Furthermore we can use this query to check if there is a certain element in the array:

```javascript
if (fruits.indexOf('avocado') > -1) {
    console.log('We have an avocado!');
}
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)


#5. Array.find() – Search elements in the array
With this function we can also check if there is a certain element in the array. It always returns us __the first occurrence__ in the array to which our condition applies.

Our instruction is: “Give me back an element with “o” in its name”. We get the first result in our `result` variable.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
const result = fruits.find((fruit) => {
    return fruit.indexOf('o') > -1;
});
console.log(result); // Output: avocado
```

Again, we can outsource more complex statements to an extra callback function.

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)


#6. Array.sort() – Sorting values made easy
This function can sort our array. So we do not need to program our own sorting algorithm.

To do this, this function converts the elements of the array into strings and compares them using their UTF-16 codepoints. Therefore, strings starting with numbers are always placed __before__ all string elements.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
let sortedFruits = fruits.sort();
console.log(sortedFruits);  // Output: ["apple", "avocado", "banana", "cherry", "grapefruit", "melon"]
```

In addition, a callback can also be specified here, where you specify your own Compare function by which the elements are to be sorted.

For example, the elements can easily be sorted in descending instead of ascending order. The return value of the callback must always be 1 or -1.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];
let sortedFruitsDESC = fruits.sort(sortDESC);
function sortDESC(a, b) {
  return a < b ? 1 : -1;
}
console.log(sortedFruitsDESC);  // Output: ["melon", "grapefruit", "cherry", "banana", "avocado", "apple"]
```

Of course, the same works for other data types, such as numbers or objects. This can look like this.

```javascript
let fruits = [
    {name: 'banana', amount: '2'},
    {name: 'apple', amount: '22'},
    {name: 'avocado', amount: '404'},
    {name: 'cherry', amount: '83'},
    {name: 'grapefruit', amount: '26'},
    {name: 'melon', amount: '42'}
];

let sortedFruitsByAmount = fruits.sort(sortDESC);

function sortDESC(a, b) {
  return a.amount > b.amount ? 1 : -1;
}

console.log(sortedFruitsByAmount);
// Output:
// 0: {name: "banana", amount: "2"}
// 1: {name: "apple", amount: "22"}
// 2: {name: "grapefruit", amount: "26"}
// 3: {name: "avocado", amount: "404"}
// 4: {name: "melon", amount: "42"}
// 5: {name: "cherry", amount: "83"}
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)


#7. Array.reverse() – Reverse everything
This function is quickly explained: The order of the elements is simply reversed.

```javascript
let fruits = [
    'banana',
    'apple',
    'avocado',
    'cherry',
    'grapefruit',
    'melon'
];

let reversedFruits = fruits.reverse();
console.log(reversedFruits);  // Output: ["melon", "grapefruit", "cherry", "avocado", "apple", "banana"]
```

There are no other parameters for this, but you will need this function sooner or later. At least you will save the following lines.

```javascript
function reverse(array) {
  let reverse = [];
  for(let i = array.length - 1; i >= 0; i--) {
    reverse.push(array[i]);
  }
  return reverse;
}
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)


#8. Array.concat() – Connecting arrays
With this method you can connect two or more arrays in a row. This can be useful, for example, if you evaluate filter functions and output all values to the visitor in one array.

```javascript
let fruitsOne = [
    'banana',
    'apple',
    'avocado'
];
let fruitsTwo = [
    'cherry',
    'grapefruit',
    'melon'
];

let concatedFruits = fruitsOne.concat(fruitsTwo);

console.log(concatedFruits);  // Output: ["banana", "apple", "avocado", "cherry", "grapefruit", "melon"]
```

[Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)


#Conclusion
Well, as you can see there are very useful JavaScript array functions. Many of them can be implemented with just a few lines of code and give super great results.

On with the [best examples of how to learn Vue.js](https://webdeasy.de/en/3-practical-examples-vue-js/), right? 😉