Mastering Array Methods (map, filter, reduce)

Advanced Array Methods

Advanced array methods: map, filter, reduce, find, etc.

Example Data

const gommageResistance = [85, 92, 78, 96, 89, 73, 91, 88];
const expeditionMembers = [
    { name: 'Gustave', resistance: 85, role: 'Engineer' },
    { name: 'Maelle', resistance: 92, role: 'Explorer' },
    { name: 'Lune', resistance: 78, role: 'Researcher' },
    { name: 'Sciel', resistance: 96, role: 'Teacher' },
    { name: 'Verso', resistance: 89, role: 'Mysterious' },
    { name: 'Renoir', resistance: 73, role: 'Savior' },
    { name: 'Monoco', resistance: 91, role: 'Gestral' }
];

1. MAP() - Transform Each Element

// Goal: Creates a new array by applying a function to each element
// WARNING: Does NOT modify the original array

const enhancedResistance = gommageResistance.map(resistance => resistance + 10);
console.log("Resistance after training:", enhancedResistance);

const lumiereCodes = expeditionMembers.map(member => member.name.toUpperCase());
console.log("Lumière codes:", lumiereCodes);

const expeditionCards = expeditionMembers.map((member, index) =>
    `#${index + 1}: ${member.name} - ${member.resistance}/100 resistance (${member.role})`
);
console.log("Anti-Gommage cards:", expeditionCards);

2. FILTER() - Filter by a Condition

// Goal: Returns a new array with the elements that pass the test
// WARNING: Does NOT modify the original array

const eliteSurvivors = gommageResistance.filter(resistance => resistance >= 90);
console.log("Survivors (≥90):", eliteSurvivors);

const researchers = expeditionMembers.filter(member => member.role === 'Researcher');
console.log("Research team:", researchers);

const lumiereVeterans = expeditionMembers.filter(member => member.resistance > 85 && member.name.length > 4);
console.log("Lumière veterans:", lumiereVeterans);

3. REDUCE() - Reduce to a Single Value

// Goal: Accumulates the array's elements into a single value
// Parameters: (accumulator, currentValue, index, array)

const averageResistance = gommageResistance.reduce((sum, resistance) => sum + resistance, 0) / gommageResistance.length;
console.log("Average resistance:", averageResistance.toFixed(2));

const bestResistance = gommageResistance.reduce((max, resistance) => resistance > max ? resistance : max, 0);
console.log("Best resistance:", bestResistance);

const roleBreakdown = expeditionMembers.reduce((counter, member) => {
    counter[member.role] = (counter[member.role] || 0) + 1;
    return counter;
}, {});
console.log("Breakdown by role:", roleBreakdown);

4. FOREACH() - Run an Action on Each Element

// Goal: Runs a function for each element
// WARNING: Returns NOTHING (undefined)

console.log("Mission report:");
expeditionMembers.forEach((member, position) => {
    const status = member.resistance >= 90 ? "Hero" :
                   member.resistance >= 80 ? "Fighter" : "In danger";
    console.log(`   ${position + 1}. ${member.name}: ${member.resistance}/100 ${status}`);
});

5. FIND() - Find the First Matching Element

// Goal: Returns the FIRST element that satisfies the condition
// Returns undefined if nothing is found

const firstHero = gommageResistance.find(resistance => resistance >= 95);
console.log("First hero (≥95):", firstHero);

const gustave = expeditionMembers.find(member => member.name === 'Gustave');
console.log("Engineer Gustave:", gustave);

const gestral = expeditionMembers.find(member => member.role === 'Gestral');
console.log("Gestral warrior:", gestral);

6. SOME() - Check Whether AT LEAST ONE Element Matches

// Goal: Returns true if AT LEAST ONE element satisfies the condition

const hasHeroes = gommageResistance.some(resistance => resistance >= 95);
console.log("Are there any heroes (≥95)?", hasHeroes);

const hasGestrals = expeditionMembers.some(member => member.role === 'Gestral');
console.log("Are there any Gestrals on the team?", hasGestrals);

7. EVERY() - Check Whether ALL Elements Match

// Goal: Returns true if ALL elements satisfy the condition

const allWillSurvive = gommageResistance.every(resistance => resistance >= 70);
console.log("Will everyone survive the Gommage (≥70)?", allWillSurvive);

const allHaveResistance = expeditionMembers.every(member => member.resistance > 0);
console.log("Does everyone have some resistance?", allHaveResistance);

8. INCLUDES() - Check Whether a Value Is Present

// Goal: Checks whether the array contains a specific value

const lumiereArtifacts = ['Brush', 'Canvas', 'Luminoid', 'Crystal', 'Shadow'];
console.log("Lumière artifacts:", lumiereArtifacts);
console.log("Contains 'Brush'?", lumiereArtifacts.includes('Brush'));
console.log("Contains 'Gommage'?", lumiereArtifacts.includes('Gommage'));

9. INDEXOF() - Find the Index of a Value

// Goal: Returns the index of a value, or -1 if it is not found

const zones = ['Lumière', 'Shadow', 'Clair-Obscur', 'Void'];
console.log("Explored zones:", zones);
console.log("Index of 'Clair-Obscur':", zones.indexOf('Clair-Obscur'));
console.log("Index of 'Paradise':", zones.indexOf('Paradise')); // -1

10. SPLIT() - Split a String into an Array

// Goal: Splits a string into an array
// WARNING: This is a String method, not an Array method!

const prophecy = "The Paintress will erase every inhabitant of Lumière";
const words = prophecy.split(" ");
console.log("Prophecy:", prophecy);
console.log("Words of the prophecy:", words);

const coordinates = "Expedition@Lumière.world";
const [mission, place] = coordinates.split("@");
console.log(`Mission: ${mission}, Place: ${place}`);

11. JOIN() - Join Elements into a String

// Goal: Joins the array's elements into a string

const powers = ['Resistance', 'Vision', 'Combat', 'Magic'];
const arsenal = powers.join(" • ");
console.log("Expedition arsenal:", arsenal);

const journey = ['Lumière', 'Shadow', 'Clair-Obscur', 'Paintress-Lair'];
const route = journey.join(" > ");
console.log("Expedition route:", route);

12. SPLICE() - Modify the Array in Place

// Goal: Adds/removes elements of the array
// WARNING: MODIFIES the original array!
// Syntax: splice(start, deleteCount, ...itemsToAdd)

const threats = ['Gommage', 'Shadow', 'Paintress', 'Void'];
console.log("Threats before:", [...threats]);

// Replace 'Paintress' with 'Hope'
const neutralized = threats.splice(2, 1, 'Hope');
console.log("Threats after neutralization:", threats);
console.log("Neutralized threats:", neutralized);

// Add a new threat
threats.splice(2, 0, 'Corruption');
console.log("After discovery:", threats);

13. SLICE() - Extract a Portion

// Goal: Returns a shallow copy of a portion of the array
// WARNING: Does NOT modify the original array

const timeline = ['Creation', 'Golden Age', 'Decline', 'Gommage', 'Resistance', 'Expedition'];
console.log("Full history:", timeline);

const origins = timeline.slice(0, 3);
console.log("First 3 eras:", origins);

const endOfTimes = timeline.slice(-3);
console.log("Last 3 eras:", endOfTimes);

const currentCrisis = timeline.slice(2, 5);
console.log("Current crisis:", currentCrisis);

14. SET - Collection of Unique Values

// Goal: Stores only unique values (no duplicates)
// WARNING: This is not an Array method, but it is very useful with arrays!

const gommageTestimonies = [85, 90, 85, 92, 90, 88, 92, 85];
console.log("Testimonies with duplicates:", gommageTestimonies);

const uniqueTestimonies = new Set(gommageTestimonies);
console.log("Set of unique testimonies:", uniqueTestimonies);

// Convert back to an array
const evidence = [...uniqueTestimonies];
console.log("Evidence without duplicates:", evidence);

// Check whether a value is present
console.log("Does the evidence contain 90?", uniqueTestimonies.has(90));
console.log("Number of unique pieces of evidence:", uniqueTestimonies.size);

15. OBJECT.KEYS() / VALUES() / ENTRIES()

// Goal: Extract the keys, the values, or the key-value pairs of an object

const paintressMission = {
    name: 'Expedition-33',
    target: 'Paintress',
    status: 'In-progress',
    difficulty: 5,
    urgent: true
};

console.log("Mission:", paintressMission);
console.log("Mission keys:", Object.keys(paintressMission));
console.log("Mission details:", Object.values(paintressMission));
console.log("Full data:", Object.entries(paintressMission));

// Mission report
const missionReport = Object.entries(paintressMission)
    .map(([key, value]) => `${key}: ${value}`)
    .join(' | ');
console.log("Formatted report:", missionReport);

16. FLAT() - Flatten Nested Arrays

// Goal: Flattens nested arrays

const lumiereHierarchy = [
    ['Citizens', 'Artisans'],
    ['Expeditioners', ['Gustave', 'Maelle']],
    [['Verso', 'Sciel'], 'Paintress']
];

console.log("Nested hierarchy:", lumiereHierarchy);
console.log("Flattened one level:", lumiereHierarchy.flat());
console.log("All the characters:", lumiereHierarchy.flat(2));

// Tidy up the ranks
const mixedRanks = [
    ['Novice', 'Apprentice'],
    [],
    ['Veteran'],
    ['Master', ['Legend', 'Myth']]
];
const allRanks = mixedRanks.flat(2).filter(rank => rank);
console.log("All ranks:", allRanks);