LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 12 of 25

Array Methods Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Array Methods · Study material

Modern JavaScript processes data with array methods instead of hand-written loops: map to transform, filter to select, reduce to summarise, find to search, some and every to check. They are used in every React component and Node.js service – and in almost every JavaScript interview, usually with a twist: reduce without an initial value, forEach returning undefined, ["1", "2", "3"].map(parseInt), or every on an empty array. This topic covers each method, how they combine and the traps around them. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

The core methods

MethodReturnsUse it to
forEach(fn)undefinedrun a side effect for each element
map(fn)new array, same lengthtransform every element
filter(fn)new array of the elements where fn is truthyselect elements
reduce(fn, initial)one value of any typesum, count, group, build objects
find(fn) / findLast(fn)first / last matching element or undefinedlook up one item
findIndex(fn) / findLastIndex(fn)index or -1locate one item
some(fn) / every(fn)boolean"any?" / "all?"
flat(depth) / flatMap(fn)new flattened arrayremove nesting

None of these change the original array (unless the callback does). sort and reverse do – use toSorted / toReversed for copies.

const prices = [120, 450, 80, 999];
const withGst = prices.map((p) => Math.round(p * 1.18));   // transform every element → same length
const above100 = prices.filter((p) => p > 100);            // keep elements where the callback is truthy
const total = prices.reduce((sum, p) => sum + p, 0);       // combine everything into one value
console.log(withGst, above100, total);
console.log(prices);                                       // none of them changed the original

Output

[ 142, 531, 94, 1179 ] [ 120, 450, 999 ] 1649
[ 120, 450, 80, 999 ]

Callback arguments

Every callback receives (element, index, array). That is useful (the index is often needed) and dangerous when you pass a function that takes optional extra parameters: map(parseInt) passes the index as parseInt's radix. Pass a wrapper (s => parseInt(s, 10)) or a one-argument function such as Number.

// Callbacks receive (element, index, array)
console.log(["a", "b"].map((value, index, arr) => `${index}:${value}/${arr.length}`));
// So map(parseInt) calls parseInt("1", 0), parseInt("2", 1), parseInt("3", 2) – the index becomes the radix
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));                  // Number takes one argument: safe

Output

[ '0:a/2', '1:b/2' ]
[ 1, NaN, NaN ]
[ 1, 2, 3 ]

Searching: find, findIndex, some and every

find returns the element itself (not an array) or undefined; findIndex returns -1 when nothing matches; findLast and findLastIndex search from the end. some stops at the first truthy result and every at the first falsy one. On an empty array, some is false and every is true ("all of nothing").

const users = [
  { id: 1, name: "Asha", active: true },
  { id: 2, name: "Ravi", active: false },
  { id: 3, name: "Meera", active: true },
];
console.log(users.find((u) => u.active).name, users.findLast((u) => u.active).name);
console.log(users.findIndex((u) => u.id === 2), users.find((u) => u.id === 9));
// some: at least one; every: all of them. An empty array: some → false, every → true
console.log(users.some((u) => !u.active), users.every((u) => u.name.length >= 4), [].every((x) => x > 100));

Output

Asha Meera
1 undefined
true true true

reduce in depth

arr.reduce((accumulator, element, index, array) => newAccumulator, initialValue). The callback must return the accumulator for the next step. With an initial value, the first call gets it and the first element; without one, the first element becomes the accumulator and processing starts at the second – and an empty array without an initial value throws a TypeError. Always pass an initial value unless you are certain the array is non-empty and of the right type. reduceRight works from the end.

const orders = [
  { city: "Pune", amt: 500 },
  { city: "Delhi", amt: 300 },
  { city: "Pune", amt: 200 },
];
// reduce into an object: totals per city
const byCity = orders.reduce((acc, o) => {
  acc[o.city] = (acc[o.city] ?? 0) + o.amt;
  return acc;                                   // always return the accumulator
}, {});
// without an initial value, the first element is the starting accumulator
const max = [4, 9, 2].reduce((a, b) => Math.max(a, b));
console.log(byCity, max);

Output

{ Pune: 700, Delhi: 300 } 9

flat and flatMap

flat(depth = 1) removes that many levels of nesting (Infinity for all). flatMap(fn) maps and then flattens one level, so a callback can return an empty array to drop an element or several items to expand it.

const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(), nested.flat(Infinity));          // default depth is 1
// flatMap = map, then flat by one level: one input can produce 0, 1 or many outputs
console.log(["hello world", "hi"].flatMap((s) => s.split(" ")));
console.log([1, 2, 3].flatMap((n) => (n % 2 ? [n, n * 10] : [])));

Output

[ 1, 2, [ 3, [ 4 ] ] ] [ 1, 2, 3, 4 ]
[ 'hello', 'world', 'hi' ]
[ 1, 10, 3, 30 ]

Sorting objects and chaining

A comparator returns a negative number to put a first, a positive number to put b first, and 0 to keep their order (sort is stable). Combine criteria with ||: if the first difference is 0, the second decides. Because these methods return arrays, they can be chained into readable pipelines.

const team = [
  { name: "Ravi", score: 72 },
  { name: "Asha", score: 91 },
  { name: "Kiran", score: 72 },
];
// Highest score first; ties broken alphabetically by name. toSorted leaves team unchanged.
const ranking = team
  .toSorted((a, b) => b.score - a.score || a.name.localeCompare(b.name))
  .map((p, i) => `${i + 1}. ${p.name} (${p.score})`);
console.log(ranking.join("\n"));

Output

1. Asha (91)
2. Kiran (72)
3. Ravi (72)

forEach vs map

forEach is for side effects and always returns undefined; map builds a new array from return values. An arrow function with braces needs return – without it every element maps to undefined.

const viaForEach = [1, 2, 3].forEach((n) => n * 2);   // forEach always returns undefined
const viaMap = [1, 2, 3].map((n) => n * 2);
const forgotReturn = [1, 2, 3].map((n) => { n * 2; }); // braces need an explicit return
console.log(viaForEach, viaMap, forgotReturn);

Output

undefined [ 2, 4, 6 ] [ undefined, undefined, undefined ]

Common mistakes

  • reduce without an initial value – crashes on empty arrays and starts with an object instead of 0 for arrays of objects.
  • Forgetting to return the accumulator – the next step receives undefined.
  • Using forEach to build an array – it returns undefined; use map.
  • map(parseInt) – the index becomes the radix.
  • if (arr.filter(...)) – an empty array is still truthy; use some.
  • find(...).prop without a check – find may return undefined.
  • Sorting strings with a - b – NaN; use localeCompare.

Key points to remember

  • map → same length; filter → subset; reduce → one value.
  • Callbacks get (element, index, array).
  • find returns an element or undefined; findIndex returns -1 when missing.
  • some stops at the first true; every stops at the first false; every([]) is true.
  • Always give reduce an initial value and return the accumulator.
  • flat defaults to depth 1; flatMap = map + flat(1).
  • forEach returns undefined and cannot be stopped.

Frequently asked questions

Are array methods slower than for loops?

Slightly, in tight hot loops, but rarely enough to matter. They are clearer and less error-prone. For very large data, combine steps in one reduce or loop instead of a long chain.

Can I use async functions with map?

map returns an array of promises; wrap it in await Promise.all(arr.map(async …)). forEach does not wait for async callbacks at all.

Should I use reduce for everything?

No. Use map, filter, find, some and every when they express the intent; reduce is best for building one value such as a sum, a count or a lookup object.

Where can I learn more?

Read map, filter and reduce and Higher-Order Functions in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links