DEV Community

Cover image for Useful JavaScript Arrays Methods
Adrian | Founder of BigDevSoon
Adrian | Founder of BigDevSoon

Posted on • Edited on

Useful JavaScript Arrays Methods

Originally posted on bigsondev.com


Arrays exist in every programming language. It's a data structure best suited for storing multiple values. And, for doing various operations on these values, often called as a collection.


Introduction

It's always best to learn by doing. Take a look at the below code example, study, and execute it step by step.

// Create an array of 3 items using [ ] brackets
const friends = ["John", "Joe", "Jane"];

// Here we have a "collection" of friends declared as an array
console.log(friends); // ["John", "Joe", "Jane"]

// Array is indexed from 0 and not from 1
// 0 -> "John", 1 -> "Joe", 2 -> "Jane"

// Access particular friend from an array
console.log(friends[0]); // "John"
console.log(friends[1]); // "Joe"
console.log(friends[2]); // "Jane"
console.log(friends[3]); // undefined (we don't have 4th item)

// Get length of the array
console.log(friends.length); // 3 (as we have 3 items in the friends array)

// Safe way to get the last item of an array 
console.log(friends[friends.length - 1]) // "Jane"

// Directly change an array item
friends[0] = 'Pedro';
console.log(friends); // ["Pedro", "Joe", "Jane"]

// Directly push to an array
friends.push('Max');
console.log(friends); // ["Pedro", "Joe", "Jane", "Max"]

// Directly remove the item from an array
friends.pop();
console.log(friends); // ["Pedro", "Joe", "Jane"]
Enter fullscreen mode Exit fullscreen mode

Let's learn how to utilize array methods to do useful operations on the entire collection.


Useful Array Methods & Avoiding Loops

Changing original array items, pushing to it results in mutating which can introduce unwanted, side effects and makes code much more difficult to maintain. Let's aim for a declarative, functional approach with immutability in mind. Go through the below examples to see how we can easily achieve that with less code and more semantics.

1. .map()

Assignment: Multiply all numbers by 2.

Loop solution:

const numbers = [5, 10, 15, 20];

for (let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i] * 2;
}

console.log(numbers); // [10, 20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

Map numbers in an array:

const numbers = [5, 10, 15, 20];
const multipliedNumbers = numbers.map((number) => number * 2);

console.log(numbers); // [5, 10, 15, 20];
console.log(multipliedNumbers); // [10, 20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

2. .filter()

Assignment: Remove all numbers less or equal to 10.

Loop solution:

const numbers = [5, 10, 15, 20];
const filteredNumbers = [];

for (let i = 0; i < numbers.length; i++) {
  const currentNumber = numbers[i];

  if (currentNumber > 10) {
    filteredNumbers.push(currentNumber);
  } 
}

console.log(numbers); // [5, 10, 15, 20]
console.log(filteredNumbers); // [15, 20]
Enter fullscreen mode Exit fullscreen mode

Filter numbers in an array:

const numbers = [5, 10, 15, 20];
const filteredNumbers = numbers.filter((number) => number > 10);

console.log(numbers); // [5, 10, 15, 20]
console.log(filteredNumbers); // [15, 20]
Enter fullscreen mode Exit fullscreen mode

3. .reduce()

Assignment: Sum all numbers.

Loop solution:

const numbers = [5, 10, 15, 20];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum); // 50
Enter fullscreen mode Exit fullscreen mode

Reduce numbers to create a sum:

const numbers = [5, 10, 15, 20];
const sum = numbers.reduce((accumulator, number) => accumulator += number, 0);

console.log(sum); // 50
Enter fullscreen mode Exit fullscreen mode

4. .indexOf()

Assignment: Find an index of number 15.

Loop solution:

const numbers = [5, 10, 15, 20];
const numberToFind = 15;
let numberToFindIndex = undefined;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === numberToFind) {
    numberToFindIndex = i;
    break;
  }
}

console.log(numberToFindIndex); // 2, remember that array is indexed from 0
Enter fullscreen mode Exit fullscreen mode

Find index by using an indexOf method::

const numbers = [5, 10, 15, 20];
const numberToFind = 15;
const numberToFindIndex = numbers.indexOf(numberToFind);

console.log(numberToFindIndex); // 2, remember that array is indexed from 0
Enter fullscreen mode Exit fullscreen mode

5. .every()

Assignment: Check if all numbers are greater or equal to 10.

Loop solution:

const numbers = [5, 10, 15, 20];
const minimumValue = 10;
let isBigEnough = true;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] < minimumValue) {
    isBigEnough = false;
    break;
  }
}

console.log(isBigEnough); // false
Enter fullscreen mode Exit fullscreen mode

Check if condition is true to all numbers::

const numbers = [5, 10, 15, 20];
const minimumValue = 10;
const isBigEnough = numbers.every((number) => number >= minimumValue);

console.log(isBigEnough); // false
Enter fullscreen mode Exit fullscreen mode

6. .some()

Assignment: Check if any number is greater or equal to 10.

Loop solution:

const numbers = [5, 10, 15, 20];
const minimumValue = 10;
let isBigEnough = false;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] >= minimumValue) {
    isBigEnough = true;
    break;
  }
}

console.log(isBigEnough); // true
Enter fullscreen mode Exit fullscreen mode

Check if condition is true to any number::

const numbers = [5, 10, 15, 20];
const minimumValue = 10;
const isBigEnough = numbers.some((number) => number >= minimumValue);

console.log(isBigEnough); // true
Enter fullscreen mode Exit fullscreen mode

7. .includes()

Assignment: Check if number 15 is included in the numbers array.
Loop solution:

const numbers = [5, 10, 15, 20];
const numberToFind = 15;
let isNumberIncluded = false;

for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === numberToFind) {
  isNumberIncluded = true;
  break;
  }
}

console.log(isNumberIncluded); // true
Enter fullscreen mode Exit fullscreen mode

Check if number is included:

const numbers = [5, 10, 15, 20];
const numberToFind = 15;
const isNumberIncluded = numbers.includes(numberToFind);

console.log(isNumberIncluded); // true
Enter fullscreen mode Exit fullscreen mode

Bonus

I described couple of more methods, techniques to work with arrays, example below:

const myAnimals = ['dog', 'cat'];
const myFriendAnimals = ['bird', 'python', 'elephant'];
// Cool way to join arrays together using spread operator
const ourAnimals = [...myAnimals, ...myFriendAnimals];

console.log(ourAnimals); // ["dog", "cat", "bird", "python", "elephant"]

// Cool way to fill in array from something using .from method
const numbers = Array.from({ length: 10 }, (_, key) => key);

console.log(numbers); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

const nestedArray = [[1, 2], [3, 4], [5, 6]];
// Cool way to flatten an array using .flat method
const flatArray = nestedArray.flat();

console.log(flatArray); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Summary

I have lots of fun with immutability and enjoy it to the max. Don't remember when I wrote a loop last time. Mostly working on Frontend tho, might be totally different when working with Backend as it's all about optimizations then. Find your balance.

Declarative, functional programming is cool but there is nothing wrong with mutations too. Using break or loops might be necessary, don't limit yourself to one style. It's all about conventions when working in a team and if you mostly work solo, find what suits you the best.

There are more array methods in JavaScript, but I mostly focused on the ones which avoid mutations. I hope you learned something along the way.


I'm thinking about creating YT video series - building projects from my website, step-by-step, modern technologies, best coding practices with a thorough explanation.

If you enjoy the content and like the idea, Buy me a pizza.
Let's reach that goal together. 😊

Thanks for all the support!

Get in touch: Mentorship | Twitter | LinkedIn

Top comments (3)

Collapse
 
saradanewz profile image
SaradaNews

Nice Explanation

Collapse
 
andrewbaisden profile image
Andrew Baisden

Awesome well explained I think "some" and "every" don't get enough usage.

Collapse
 
mihara17 profile image
Michelle Te Whata

Thank you for sharing