Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to JavaScript
JavaScript Array Methods You Must Know

JavaScript Array Methods You Must Know

JavaScriptBy Muhammad Fareed
javascriptarraymethodsmust

Short answer: the array methods used most in everyday JavaScript are map (transform every item), filter (keep some items), reduce (combine into one value), find (get one item) and forEach (run code for each item). Learning these lets you replace most manual for loops with shorter, clearer code.

The examples use this data:

const products = [
  { id: 1, name: "Keyboard", price: 40, inStock: true },
  { id: 2, name: "Mouse", price: 20, inStock: false },
  { id: 3, name: "Monitor", price: 180, inStock: true },
];

map: transform every item

const names = products.map((p) => p.name);
// ["Keyboard", "Mouse", "Monitor"]

const withTax = products.map((p) => ({ ...p, price: p.price * 1.18 }));

map returns a new array of the same length and does not change the original.

filter: keep matching items

const available = products.filter((p) => p.inStock);
// Keyboard and Monitor

const cheap = products.filter((p) => p.price < 50);

reduce: combine into one value

const total = products.reduce((sum, p) => sum + p.price, 0);
// 240

const byId = products.reduce((acc, p) => {
  acc[p.id] = p;
  return acc;
}, {});

The second argument (0, {}) is the starting value. Always provide it.

find and findIndex

const monitor = products.find((p) => p.name === "Monitor"); // the object, or undefined
const index = products.findIndex((p) => p.id === 2);         // 1, or -1

some, every and includes

products.some((p) => p.price > 100);     // true: at least one
products.every((p) => p.inStock);         // false: not all
[1, 2, 3].includes(2);                    // true

forEach: run code for each item

products.forEach((p) => console.log(p.name));

forEach returns nothing, so use map when you want a new array. It does not wait for async callbacks; see async/await in loops.

sort

[10, 9, 1].sort();                 // [1, 10, 9]  (sorts as strings!)
[10, 9, 1].sort((a, b) => a - b);  // [1, 9, 10]

products.sort((a, b) => a.price - b.price);          // cheapest first
products.sort((a, b) => a.name.localeCompare(b.name)); // by name

sort changes the array in place. To keep the original, copy first: [...products].sort(...).

slice, splice and concat

const nums = [1, 2, 3, 4, 5];

nums.slice(1, 3);        // [2, 3]  returns a copy, original unchanged
nums.splice(1, 2);       // removes 2 items at index 1, CHANGES nums
nums.concat([6, 7]);     // new array
[...nums, 6, 7];         // spread alternative

push, pop, shift, unshift

MethodEffect
push(x)Add to the end
pop()Remove from the end
unshift(x)Add to the start
shift()Remove from the start

flat, flatMap and Array.from

[1, [2, [3]]].flat();        // [1, 2, [3]]
[1, [2, [3]]].flat(Infinity); // [1, 2, 3]

["a b", "c d"].flatMap((s) => s.split(" ")); // ["a", "b", "c", "d"]

Array.from({ length: 3 }, (_, i) => i * 2); // [0, 2, 4]

Chaining

const result = products
  .filter((p) => p.inStock)
  .map((p) => p.price)
  .reduce((sum, price) => sum + price, 0);
// 220

Quick reference

GoalMethodChanges original?
Transform each itemmapNo
Keep some itemsfilterNo
Get one value from allreduceNo
First matchfindNo
Test the itemssome, everyNo
Order itemssortYes
Add or removepush, pop, spliceYes

Common mistakes

  • Using map only for side effects; use forEach or a loop.
  • Forgetting that sort() without a compare function sorts as strings.
  • Forgetting the initial value in reduce on empty arrays, which throws an error.
  • Mutating state in frameworks like React; prefer map, filter and spread, which return new arrays.

Keep a one-page summary with the array methods cheat sheet, and see modern syntax in ES6 features.

FAQs

What is the difference between map and forEach?

map returns a new array of results. forEach returns nothing and is only for running code.

What is the difference between slice and splice?

slice copies a part without changing the array. splice removes or inserts items and changes it.

How do I remove duplicates?

const unique = [...new Set(array)];

How do I sort numbers correctly?

Pass a compare function: array.sort((a, b) => a - b).