Array Methods Part 4
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 69 of 77.
Here are even more useful array methods:
1. map(callback): Creates a new array populated with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]2. filter(callback): Creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]3. reduce(callback, initialValue): Executes a reducer function on each element of the array, resulting in a single output value.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10Challenge
EasyYou are given an array numbers = [1, 2, 3, 4, 5]. Perform the following steps and print the results directly:
- Use
map()to create a new array where each number is multiplied by 3, and print the result. - Use
filter()to create a new array that only includes numbers greater than 3, and print the result.
Cheat sheet
Array methods for transforming and filtering data:
map(callback): Creates a new array by applying a function to every element:
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]filter(callback): Creates a new array with elements that pass a test:
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]reduce(callback, initialValue): Reduces an array to a single value:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10Try it yourself
let numbers = [1, 2, 3, 4, 5];This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionFunction ExpressionDefault ParametersArrow FunctionsRecap - Validation Function12Arrays Part 2
Iterating Over ArraysThe forEach Methodfor...of LoopRecap - P CounterArray SlicingArray Methods Part 3Array Methods Part 4Membership Testing