DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for JavaScript Arrays πŸ™πŸ» – Most useful functions for developers
webdeasy.de
webdeasy.de

Posted on • Originally published at webdeasy.de

JavaScript Arrays πŸ™πŸ» – Most useful functions for developers

Originally published on webdeasy.de!

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

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"]
Enter fullscreen mode Exit fullscreen mode

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

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"]
Enter fullscreen mode Exit fullscreen mode

Documentation

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.

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

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:

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"]
Enter fullscreen mode Exit fullscreen mode

Documentation

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?

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

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.

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"
Enter fullscreen mode Exit fullscreen mode

Documentation

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.

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
Enter fullscreen mode Exit fullscreen mode

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

if (fruits.indexOf('avocado') > -1) {
    console.log('We have an avocado!');
}
Enter fullscreen mode Exit fullscreen mode

Documentation

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.

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

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

Documentation

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.

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

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.

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"]
Enter fullscreen mode Exit fullscreen mode

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

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"}
Enter fullscreen mode Exit fullscreen mode

Documentation

7. Array.reverse() – Reverse everything

This function is quickly explained: The order of the elements is simply reversed.

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

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

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

function reverse(array) {
  let reverse = [];
  for(let i = array.length - 1; i >= 0; i--) {
    reverse.push(array[i]);
  }
  return reverse;
}
Enter fullscreen mode Exit fullscreen mode

Documentation

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.

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"]
Enter fullscreen mode Exit fullscreen mode

Documentation

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, right? πŸ˜‰

Top comments (0)

Thank you.

Β 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.