Home › Learn › JavaScript › Arrays

reduce, find, some, every

Lesson 19 of 40. Boil an array down to one value, or ask questions about it.

items.reduce((acc, item) => acc + item, 0) folds the array into one value: acc starts at the second argument and becomes the return value of each round. It can sum, count, find a maximum, or build an object. Always pass the starting value; without it an empty array throws.

find(fn) returns the first item for which fn is truthy (or undefined), findIndex its position, some(fn) asks whether any item passes, every(fn) whether all do.

const nums = [3, 8, 2];
console.log(nums.reduce((a, n) => a + n, 0));       // 13
console.log(nums.find((n) => n > 5));               // 8
console.log(nums.some((n) => n < 0), nums.every((n) => n > 0));   // false true

Your task

Write sum(nums) with reduce, largest(nums) returning the biggest number with reduce (and null for an empty array), firstLong(words, n) returning the first word longer than n or null, and allPositive(nums) returning whether every number is greater than zero.

Part of the final project. sum adds up a list of numbers; the receipt total is a sum. It is saved in this browser and loaded into Project: checkout when you get there.

Hint 1

nums.reduce((acc, n) => acc + n, 0)

Hint 2

if (nums.length === 0) return null; return nums.reduce((best, n) => (n > best ? n : best), nums[0]); find returns undefined when nothing matches, so use ?? null.

Show the solution
function sum(nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}

function largest(nums) {
  if (nums.length === 0) return null;
  return nums.reduce((best, n) => (n > best ? n : best), nums[0]);
}

function firstLong(words, n) {
  return words.find((w) => w.length > n) ?? null;
}

function allPositive(nums) {
  return nums.every((n) => n > 0);
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.