Javascript

Useful JavaScript Arrays Methods

Arrays exist in every programming language. It’s a data structure best suited for storing multiple values. And, for doing various operations on...

Written by Luci · 2 min read >

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"]

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]

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]

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]

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]

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

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

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

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

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

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

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

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

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

Check if number is included:

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]
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x