Power of JavaScript Arrays: 20 Practical Use Cases with Examples

You can also view the whole project in stackblitz https://stackblitz.com/edit/js-otpixp?devToolsHeight=33&embed=1&file=index.js&theme=dark



  1. Initialization and Declaration

We are going to use cars array as an example for majority of methods we present in this article.
Below code will initialize new array cars with 4 elements.

let cars = ['Audi', 'Mercedes', 'Bentley', 'Porsche'];


2. Accessing different array elements

Below console log would return Mercedes as it is second element in an array. We start counting elements in an array from 0, so element with index of 0 is first element in an array, 1 second etc.

let secondElement = cars[1];
// Display second element of an array
console.log(`Second element in an array : ${secondElement}`); // Mercedes

3. Array Length and Iteration

To loop through each element we are using for loop. To display length of an array we use cars.length property. Note if length was a method we would use length(), but length is just property on an array.

// Find length of array and loop through each element

console.log('3. Array Length and Iteration');

for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}

console.log(`Array has ${cars.length} elements`);

4. Adding and Removing Elements

We will add new car Aston Martin using method push. To remove the last element we will use pop() method. 

// Let's add new car maker into an array
cars.push('Aston Martin');

console.log(`Last entry added: ${cars[cars.length - 1]}`);

// Remove the last entry, Aston Martin
cars.pop();
console.log(`Last entry added: ${cars[cars.length - 1]}`);

5. Array elements modification Methods (map, slice, filter, charAt, reduce)

  • map method will loop through each element and will modify the entry as per callback function. 
  • slice method will return range of characters. In our case cars.slice(0,3) for Audi will return Aud. Important note is to remember that second parameter of slice method will not include that index, in other words take characters from 0 to 3 (excluding).
  • filter method returns original array elements that matches the condition, in our case we wanted all car makers that starts with letter A
  • charAt method will return single first character in our case when using charAt(0)
  • reduce is very powerfull method, it will loop throuch each element and will use output of previous calculation as an input for next calculation. In our case we extract first letter of each car maker and append it into accumulator parameter


// map method will loop through each element and will modify the entry as per function
// let's loop through each element and extract first 3 letters of each car maker

let carsFirstThreeLetters = cars.map((car) => car.slice(0, 3));

for (let i = 0; i < carsFirstThreeLetters.length; i++) {
console.log(carsFirstThreeLetters[i]);
}

// slice function return string characters that matches the index range, in our case first 3 characters

let carMakersThatStatrsWithLetterA = cars.filter(
(car) => car.charAt(0) === 'A'
);
console.log(carMakersThatStatrsWithLetterA);

// filter method returns original array elements that matches the condition, in our case we wanted all car makers that starts with letter A

const concatenatedLetters = cars.reduce((accumulator, currentCar) => {
console.log(accumulator);
console.log(currentCar);
return accumulator + currentCar.charAt(0);
}, '');

console.log(concatenatedLetters);

// reduce is very powerfull method, it will loop throuch each element and will use output of previous calculation as an input for next calculation. In our case we extract first letter of each car maker and append it into accumulator parameter

6. Searching and Sorting

Sorting our car makers array will result in alphabetical sort in ascending order.

Note it does not create new array, but sort existing one

Before sorting Mercedes is second elements. After sorting Bentley is second element.

cars.sort();

console.log(`After sorting ${cars[1]} is second element`);

// Let's look into searching technique
// Let's say we want to find if Porsche car make exists in our array

let isPorscheIndex = cars.indexOf('Porsche');
console.log(`Porsche exists and is in ${isPorscheIndex} index of cars array`);

let isMaybachIndex = cars.indexOf('Maybach');
// if element does not exists indexOf method returns -1
if (isMaybachIndex == -1) {
console.log(`Maybach does not exists`);
}

7. Array destructing assignment

Destructing assignment allows you to unpack values from arrays

let bentley;
let audi;

let carsWithoutAudiAndBentley;

// knowing that Audi is first element and Bentley second, we are expecting that those values will be now assigned to new variables
[audi, bentley, ...carsWithoutAudiAndBentley] = cars;

console.log(audi);
console.log(bentley);

console.log('Cars without Audi and Bentley');

carsWithoutAudiAndBentley.forEach((car) => {
console.log(car);
});

8. Multidimensional Arrays
You can incude array element inside an array, let’s try to group car makers into countries


let carsByCountries = [
['Tesla', 'Ford'],
['Mercedes', 'Audi'],
];

let indexForAmericanCars = 0;
let indexForGermanCars = 1;

// display american cars
console.log('Display only american cars.');
carsByCountries[indexForAmericanCars].forEach((car) => {
console.log(car);
});

9. Array conversions (join, split methods)

In this section we will convert array into strings and vice versa, we have to provide the method with separator that could be , . / etc. as long it is the same in both conversions.


console.log('Convert from array into string');

let convertedArrayIntoString = cars.join(',');

console.log(convertedArrayIntoString);

// let's convert string now back to array

let convertedStringIntoArray = convertedArrayIntoString.split(',');

console.log('Reading values from new array converted from string.');
convertedStringIntoArray.forEach((car) => {
console.log(car);
});

10. Array Spread Operator (…)

We already used this operator when we discussed destructing assignment, howeever let’s discuss in details the use of spread operator.
Spread operator simply iterated through each element.

Practical use could also be quite common when calling methods that requires multiple parameters.

Below we have an example in which we have a method that accepts 2 parameters, knowing our array have 2 elements we an use spread operator. Both uses will results in the same output of 34.


var carNumbersForManufacturesInMillions = [
{ 'Car maker': 'Audi', Quantity: 15 },
{ 'Car maker': 'Tesla', Quantity: 19 },
];

function SumNumbersForTwoManufactures(manufacture1, manufacture2) {
return manufacture1.Quantity + manufacture2.Quantity;
}

// one way of calling the method

console.log(
SumNumbersForTwoManufactures(
carNumbersForManufacturesInMillions[0],
carNumbersForManufacturesInMillions[1]
)
);

// using spread operator
console.log(
SumNumbersForTwoManufactures(...carNumbersForManufacturesInMillions)
);

11. Slice and Splice

Slice method creates a shalow copy of original array by removing elements range without modifying the original one.

console.log('1 as slice parameter');

console.log(cars.slice(1));

// Original array has not been modified

console.log('Original array has not been modified');
console.log(...cars);

// we can also selected range by passing 2 parameters
// end range is not included
console.log('1,3 as slice parameter');

console.log(cars.slice(1, 3));

// we can also start by taking elements from the end by using -index

// -2 will give us an array with 2 last values inside an array
console.log('-2 as slice parameter');
console.log(cars.slice(-2));

Splice method replaces or modifies value inside array at specified index. Keep in mind it will modify the existing array, if you want to create a new array use toSplice method instead


// let's replace Porsche with Jaguar
console.log(cars.toSpliced(3, 1, 'Jaguar'));

// let's add Jaguar after Bentley
console.log(cars.toSpliced(1, 0, 'Jaguar'));

12. Filtering arrays

Below code will return cars that length is at least 5 characters.

We are expecting to see Bentley, Mercedes and Porsche.

let carsWithNameLongerThan5Characters = cars.filter((car) => car.length > 5);

console.log(...carsWithNameLongerThan5Characters);

13. Every and Some methods

every() method will check if every element meet criteria and return boolean

some() method will check if some elements meet criteria and return boolean

If you are fammiliar with other programing languages or even have a bit of electronic background think of every() method as ALL and some() as ANY

console.log('Check if every car have more than 5 characters.');

let allCarsWithNameAtLeast5CharactersLong = cars.every(
(car) => car.length >= 5
);
console.log('All (ALL) cars have at least 5 characters?');

console.log(allCarsWithNameAtLeast5CharactersLong); // false

let someCarsWithNameAtLeast5CharactersLong = cars.some(
(car) => car.length >= 5
);
console.log('Some (ANY) of the cars have at least 5 characters?'); // true

14. Reverse any array

Very simple method to reverse order of elements inside the array.

console.log("Original order"); // Audi Bentley Mercedes Porsche
console.log(...cars);

let reversedCarsArray = cars.reverse();
console.log("Reversed order");

console.log(...reversedCarsArray); // Porsche Mercedes Bentley Audi

Please keep in mind that using reverse() method will modify original method, it’s called destructive method.

To make sure we do not modify original array and create a shallow copy instead let’s use toReversed() method

cars.reverse();
console.log("Setting original array back to default state");
console.log(...cars);

let toReversedCarsArray = cars.toReversed();
console.log("Original array is intacted");

// we call it non destructive method
console.log(...cars);

console.log("toReversed() method used");

console.log(...toReversedCarsArray);

15. Array Concatenation

concat() method will combine elements from other array

Let’s say we have japanese cars collection and we want to include elements into our original cars array

let japaneseCarsArray = ["Toyota", "Honda", "Nissan"];

let allCarsArray = cars.concat(...japaneseCarsArray);

console.log("All cars");
console.log(...allCarsArray); // Audi Bentley Mercedes Porsche Toyota Honda Nissan

// original cars array is still intact
console.log("Original cars");

console.log(...cars);

16. Find and Find Index methods

find() method will return the element if it exists in an array

find method accept callback which is just a function that we want to execute for every element in an array

// this will return Toyota, if value is not find it will return undefined
console.log(japaneseCarsArray.find(car => car === "Toyota"));

// returns undefined as Mitsubishi does not exists in our japanese array
console.log(japaneseCarsArray.find(car => car === "Mitsubishi"));

// another method is findIndex(). This method will return index of the element
// below will return 0 as it is first element in an array
console.log(japaneseCarsArray.findIndex(car => car === "Toyota"));

// -1 is returned if element does not exists in an array
console.log(japaneseCarsArray.findIndex(car => car === "Mitsubishi"));

17. Includes method

includes() method returns boolean value when element exists in an array

// below returns false
console.log(cars.includes('Toyota'));

// below returns true
console.log(cars.includes('Audi'));

18. Unique values in an array

This method will create new array from the current array but only with unique elements

// let's add Audi to our current array so we will know it contains 2 elements with the same value

cars.push("Audi");

console.log(...cars);

let uniqueCars = [...new Set(cars)];

// this array will only contain one Audi element
console.log(...uniqueCars);

19. Pop method — remove last element

// we will remove last element from an array
cars.pop();

console.log(...cars); // remove Audi as added it in 18. Unique values in an array

20. Array fill() method

This method will populate current array with provided values, it will replace each element with provided value

cars.fill("Germany");

console.log(...cars);

// we can also specify index range that we want values to be replaced
// below method will replace second and third index with value Audi (as you can see index 3 is not included, you can think of it as replace elements with value Audi from index 1 until index 3 (excluded))
cars.fill("Audi", 1,3);

console.log(...cars);



Comments