Home > Web Front-end > JS Tutorial > JavaScript Array Methods, Under the Hood, Part

JavaScript Array Methods, Under the Hood, Part

Barbara Streisand
Release: 2025-01-22 02:35:08
Original
432 people have browsed it

JavaScript Array Methods, Under the Hood, Part

This article continues our exploration of JavaScript array methods. If you're new to this series, you can find Part 1 here. We'll examine several common array methods—Math.max(), Math.min(), .reverse(), .filter(), and .reduce()—and show how to achieve the same results using for loops. This comparison will hopefully clarify how these methods function.


Math.min() and Math.max()

These methods find the smallest and largest numbers in a set, respectively. You can provide numbers directly as arguments or use an array with the spread syntax.

<code class="language-javascript">// FIND THE MINIMUM VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMinValueInArray(array) {
  let min = array[0];
  for (let i = 1; i < array.length; i++) {
    if (array[i] < min) {
      min = array[i];
    }
  }
  return min;
}
findMinValueInArray([33, -5544, 66, 55]); // returns: -5544

// Using Math.min():
function findMinValueInArray(array) {
  return Math.min(...array);
}
findMinValueInArray([33, -5544, 66, 55]); // returns: -5544</code>
Copy after login

Math.min() is clearly more concise and less error-prone. Math.max() works similarly, but its for loop implementation differs slightly:

<code class="language-javascript">// FIND THE MAXIMUM VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMaxValueInArray(array) {
  let max = array[0];
  for (let i = 1; i < array.length; i++) {
    let currentNum = array[i];
    if (currentNum > max) {
      max = currentNum;
    }
  }
  return max;
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66

// Using Math.max():
function findMaxValueInArray(array) {
  return Math.max(...array);
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66</code>
Copy after login

`.reverse()`

This method reverses the order of elements in an array, modifying the original array.

<code class="language-javascript">// REVERSE ARRAY ELEMENTS
// Using a 'for' loop:
function reverseArray(array) {
  let reversedArray = [];
  for (let i = array.length - 1; i >= 0; i--) {
    reversedArray.push(array[i]);
  }
  return reversedArray;
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]

// Using .reverse():
function reverseArray(array) {
  return array.reverse();
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]</code>
Copy after login

The built-in method is significantly more efficient and readable. The for loop approach requires creating a new array and manually pushing elements, increasing the risk of errors.

`.filter()`

This method creates a new array containing only elements that pass a provided test function.

Let's consider an array of bank accounts, each with a balance property. We'll filter for accounts with a zero balance.

<code class="language-javascript">// Using a 'for' loop:
function getClientWithNoMoney(array) {
  let acctsWithZeroBalance = [];
  for (let account of array) {
    if (account.balance === 0) {
      acctsWithZeroBalance.push(account);
    }
  }
  return acctsWithZeroBalance;
}

// Using .filter():
function getClientWithNoMoney(array) {
  return array.filter((account) => account.balance === 0);
}</code>
Copy after login

.filter() provides a much cleaner and more concise solution. The for loop requires manual array creation and element pushing, making it more prone to mistakes.

`.reduce()`

.reduce() applies a function cumulatively to the array elements, resulting in a single value.

A simple example is summing array elements, but let's calculate the average:

<code class="language-javascript">// With 'for' loop:
function getAverage(array) {
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum / array.length;
}

// Using .reduce():
function getAverage(array) {
  return array.reduce((cv, acc) => {
      return cv + acc;
    }) / array.length;
  );
}
getAverage([10, 20, 30, 40]); // returns: 25</code>
Copy after login

While the code savings aren't dramatic here, .reduce() still improves readability and reduces the potential for errors compared to the for loop approach.


These examples illustrate the advantages of using built-in JavaScript array methods. While for loops provide fundamental control, the methods offer conciseness, readability, and reduced error potential. If you have questions about other array methods, please leave a comment. Share this article if you found it helpful! Part 1 of this series is available here.

Thanks for reading!

Originally published to Medium for JavaScript in Plain English on February 13, 2023

The above is the detailed content of JavaScript Array Methods, Under the Hood, Part. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template