QuestenaPractice that shows what to review next
Topic lesson

Array methods: choose by the result you need

About 6 min

Questions stay in the language in which they were published.

These questions ask you to predict the result of common array methods and distinguish methods with similar callbacks. Start by naming the requested result shape: transformed values, retained elements, one match, an index, a boolean, one accumulated value, or a new combined array.

Match the method to its result shape

Method familyProcedure and small example
map and filtermap collects callback results into a new array; [2, 5].map(Number.isInteger) produces [true, true]. filter keeps original elements whose callback result is truthy; if isEven tests x % 2 === 0, [2, 5, 8].filter(isEven) produces [2, 8].
find and findIndexStop at the first qualifying element. find returns that element or undefined; findIndex returns its position or -1. Keep element and position results separate.
includes and indexOfincludes reports a boolean and can match NaN through SameValueZero. indexOf reports the first position or -1 and does not match NaN when NaN is the search value.
some and everysome asks whether at least one element passes; every asks whether no tested element fails. On [], some is false and every is true.
reduceCarry one accumulator through the elements. With an explicit initial value, start there; without one on a nonempty array, begin with the first element. If add returns sum + x, [2, 3].reduce(add, 10) produces 15.
forEachVisit elements for effects, but do not collect callback returns. Even if each callback computes a value, the forEach call returns undefined.
concat and flatconcat creates a shallow combined array and leaves inputs unchanged. flat creates a new array and, by default, removes one nesting level rather than every level.

The tempting wrong routes

Try it

Question 50

Given [1, 2, 3, 4].filter(x => x > 2), which result is returned?

  1. [false, false, true, true]
  2. [3, 4]
  3. [1, 2]
  4. true
Question 57

Which statements about reduce are true? Select all that apply.

  1. It always returns an array
  2. It always requires an explicit initial value
  3. It combines elements into one accumulated result
  4. A supplied initial value starts the accumulator
Question 59

After result = [1].concat([2]), which statement is correct?

  1. result is [1, 2], and both inputs are unchanged
  2. the first input becomes [1, 2]
  3. result is the number 2
  4. the second input becomes empty
Start drillPractice this topic
Array methods: choose by the result you need · Questena