JavaScript array methods explained simply

JavaScript Array Methods Explained Simply

JavaScript array methods explained simply

Arrays are everywhere in JavaScript: shopping carts, lists of blog posts, search results, and game scores are all natural fits. JavaScript provides many built-in array methods, but you only need a handful for most everyday tasks. This guide explains those essentials in plain language, with examples you can try in a browser console or a Node.js file.

A Quick Refresher on Arrays

An array is an ordered list of values. Each value has an index, starting from zero:

const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3

Many methods take a callback — a small function that runs once per item, usually receiving the current item (and sometimes its index and the whole array).

Note the distinction between methods that change the original array (mutation, e.g. push, pop, sort) and methods that return a new one (e.g. map, filter, slice). Non-mutating methods usually make code easier to reason about.

map: Transform Every Item

The map method creates a new array by transforming each item in the original array. It does not change the original.

const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);

console.log(doubled); // [2, 4, 6]
console.log(numbers); // [1, 2, 3]

Use map when you want the same number of items back, but in a different form. For example, you might turn a list of user objects into a list of names:

const users = [
  { name: "Ayesha", age: 24 },
  { name: "Bilal", age: 31 },
];

const names = users.map((user) => user.name);
console.log(names); // ["Ayesha", "Bilal"]

If you find yourself looping just to push transformed values into a new array, map is the cleaner replacement.

filter: Keep Only What Matches

The filter method creates a new array containing only the items that pass a test. The test is a function that returns true or false.

const scores = [45, 82, 67, 91, 38];
const passing = scores.filter((score) => score >= 50);

console.log(passing); // [82, 67, 91]

Like map, filter leaves the original unchanged. You can also combine methods — filter first, then map:

const products = [
  { name: "Keyboard", inStock: true, price: 40 },
  { name: "Mouse", inStock: false, price: 25 },
  { name: "Monitor", inStock: true, price: 180 },
];

const availableNames = products
  .filter((product) => product.inStock)
  .map((product) => product.name);

console.log(availableNames); // ["Keyboard", "Monitor"]

Chaining like this reads almost like a sentence.

forEach: Do Something with Each Item

The forEach method runs a function once for each item, but it does not return a new array. Use it when you want to perform an action, such as logging values or updating the page, rather than building a new list.

const colours = ["red", "green", "blue"];

colours.forEach((colour) => {
  console.log(colour);
});

Rule of thumb: if you need a new array, use map; if you only need side effects such as printing, use forEach.

find and findIndex: Locate One Item

Sometimes you do not want a whole filtered list — you just want the first match. That is what find does. It returns the first item that passes the test, or undefined if nothing matches.

const books = [
  { title: "Clean Code", author: "Robert Martin" },
  { title: "Eloquent JavaScript", author: "Marijn Haverbeke" },
];

const book = books.find((b) => b.title === "Clean Code");
console.log(book); // { title: "Clean Code", author: "Robert Martin" }

If you need the position rather than the value, use findIndex, which returns the index or -1 when there is no match:

const index = books.findIndex((b) => b.author === "Marijn Haverbeke");
console.log(index); // 1

Use find for a lookup by id or another unique value; use filter when you expect several matches.

reduce: Combine Items into One Value

The reduce method is the most flexible, and often the most confusing at first. It walks through an array and combines all items into a single result, such as a total, an average, or a new object.

const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => sum + price, 0);

console.log(total); // 60

Here, sum is the running total, called the accumulator, and 0 is its starting value. On each step, the function adds the current price to the sum.

Reduce can also count or group items. For example, counting how many times each word appears:

const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];

const counts = words.reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});

console.log(counts); // { apple: 3, banana: 2, cherry: 1 }

Sometimes a simple loop is clearer, but for totals and summaries reduce is worth learning.

Other Methods Worth Knowing

A few more methods round out your toolkit: includes checks whether an array contains a value ([“javascript”, “node”, “web”].includes(“node”) is true).

slice returns a copy of part of an array without changing the original (letters.slice(1, 3) returns [“b”, “c”] for [“a”, “b”, “c”, “d”]), and join turns an array into a string with a separator ([“Hello”, “world”].join(” “) gives “Hello world”).

Finally, sort changes the original array and by default sorts values as strings, so for numbers pass a comparison function: nums.sort((a, b) => a – b). Without it, 10 would come before 2, because “10” sorts before “2” as text.

Choosing the Right Method

When unsure, ask what result you want: same-length transformed list → map; smaller list → filter; one item → find; one combined value → reduce; just do something per item → forEach.

Thinking in terms of the result, rather than loop steps, leads to code that is easier to read and change.

Conclusion

You do not need to memorise every method. Start with map, filter, forEach, find, and reduce, practise by rewriting a few loops with them, and note whether each returns a new array or changes the original. With a little practice, your code will become noticeably cleaner.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *