Reading history

JavaScript Arrays and Array Methods: map, filter, reduce

4 min read 0 views

Learn JavaScript arrays: indexes, push and pop, includes, slice, map, filter, reduce, find and sorting numbers correctly.

An array is an ordered list of values kept in one variable: a list of names, a set of marks, the items in a shopping cart. Each value sits at a numbered position called an index, starting from 0. JavaScript arrays grow and shrink as needed and come with built-in methods such as map(), filter() and reduce() that replace many hand-written loops.

In this lesson you will learn

  • Creating arrays and reading items by index
  • Adding and removing items with push, pop, shift and unshift
  • Searching with includes, indexOf and find
  • Transforming data with map, filter and reduce
  • Sorting numbers correctly

Creating and Changing Arrays

const colors = ["red", "green", "blue"];
console.log(colors[0], colors[colors.length - 1], colors.length);

colors.push("yellow");      // add to the end
colors.unshift("black");    // add to the start
console.log(colors);

const last = colors.pop();  // remove from the end
const first = colors.shift(); // remove from the start
console.log(last, first, colors);

console.log(colors.includes("green"), colors.indexOf("blue"));
console.log(colors.slice(0, 2));       // copy part of the array
console.log(colors.join(" | "));

Output

red blue 3
[ 'black', 'red', 'green', 'blue', 'yellow' ]
yellow black [ 'red', 'green', 'blue' ]
true 2
[ 'red', 'green' ]
red | green | blue
  • Write arrays with square brackets. colors[0] is the first item and colors[colors.length - 1] is the last.
  • push() and pop() work at the end; unshift() and shift() work at the start. pop() and shift() return the item they removed.
  • includes() answers yes or no; indexOf() gives the position, or -1 if the item is missing.
  • slice(start, end) copies part of the array without changing it; the end index is not included.
  • join() turns the array into one string with a separator.

map, filter, reduce and sort

const marks = [72, 45, 88, 39, 91, 60];

const curved = marks.map((m) => m + 5);
const passed = marks.filter((m) => m >= 50);
const total = marks.reduce((sum, m) => sum + m, 0);
const firstHigh = marks.find((m) => m > 85);
const allPositive = marks.every((m) => m > 0);

console.log("curved:", curved);
console.log("passed:", passed);
console.log("average:", (total / marks.length).toFixed(1));
console.log("first above 85:", firstHigh, "| all positive:", allPositive);

console.log([10, 9, 100, 1].sort());                 // text order!
console.log([10, 9, 100, 1].sort((a, b) => a - b));  // numeric order

Output

curved: [ 77, 50, 93, 44, 96, 65 ]
passed: [ 72, 88, 91, 60 ]
average: 65.8
first above 85: 88 | all positive: true
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
  • map() builds a new array by applying a function to every item.
  • filter() builds a new array with only the items for which the function returns true.
  • reduce() combines all items into one value. Here sum starts at 0 and each mark is added to it.
  • find() returns the first matching item; every() and some() test whether all or any items match.
  • By default sort() compares items as text, so 100 comes before 9. Pass a compare function, (a, b) => a - b, to sort numbers. Note that sort() changes the original array.

Array Method Cheat Sheet

MethodReturnsChanges original?
push, unshiftNew lengthYes
pop, shiftRemoved itemYes
splice(i, n)Removed itemsYes
sort, reverseThe same arrayYes
slice, concatNew arrayNo
map, filterNew arrayNo
reduce, find, joinA single valueNo
forEachundefinedNo

Common Mistakes

  1. Reading arr[arr.length], which is one past the end and gives undefined.
  2. Sorting numbers without a compare function.
  3. Expecting map() to change the original; it returns a new array that you must store.
  4. Comparing arrays with ===: [1] === [1] is false because they are two different objects.

Practice Exercises

Exercise 1. From [3, 8, 12, 5, 20], make a new array of only the even numbers, each doubled.

Show answer
const result = [3, 8, 12, 5, 20].filter((n) => n % 2 === 0).map((n) => n * 2);
console.log(result); // [16, 24, 40]

Exercise 2. Find the largest number in an array using reduce().

Show answer
const nums = [14, 3, 27, 9];
const max = nums.reduce((best, n) => (n > best ? n : best), nums[0]);
console.log(max); // 27

Frequently Asked Questions

How do I copy an array?

Use the spread syntax, const copy = [...original];, or original.slice(). Both make a shallow copy: nested objects are still shared.

How do I remove duplicates from an array?

Convert it to a Set and back: const unique = [...new Set(arr)];.

Summary

  • Arrays hold ordered values; indexes start at 0 and length gives the size.
  • push/pop and unshift/shift add and remove at the ends.
  • map, filter and reduce transform data without changing the original.
  • Sort numbers with sort((a, b) => a - b).

Next: JavaScript Objects.

Lessons are also marked complete when you click Next.

Leave a Reply

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