My Favorite 10 Array Methods
- map(): The Shape-Shifter
Once upon a time in the kingdom of Arrays, a group of numbers wanted a glow-up. Enter the powerful sorcerermap()
. With a flick of their wand, every number was doubled!
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled);
// [2, 4, 6, 8]
“From zeros to heroes, we are twice as nice!" exclaimed the numbers.
- filter(): The Gatekeeper
A party was happening, but only the even numbers could get past the velvet rope.filter()
played the bouncer, checking IDs.
let guests = [1, 2, 3, 4, 5];
let evenGuests = guests.filter(num => num % 2 === 0);
console.log(evenGuests);
// [2, 4]
Sorry oddballs, this party is for evens only.
- reduce(): The Wise Sage
When the numbers couldn’t decide who was the most important, they turned to the ancient sagereduce()
for wisdom.
let coins = [1, 2, 3, 4];
let treasure = coins.reduce((total, coin) => total + coin, 0);
console.log(treasure);
// 10
“Together, we are richer!" declared the coins.
- forEach(): The Chatterbox
forEach()
loved gossiping and couldn’t keep any secrets.
let friends = ["Tahaa", "Akshay", "Aditya"];
friends.forEach(friend => console.log(friend));
// Tahaa
// Akshay
// Aditya
“I’ll tell you everything I know!" said forEach.
- find(): The Detective
find()
was on a mission to uncover the first treasure worth over 50 gold coins.
let treasures = [30, 55, 70];
let firstBigTreasure = treasures.find(treasure => treasure > 50);
console.log(firstBigTreasure);
// 55
Case cracked! Found it! exclaimed find.
- findIndex(): The Tracker
The sidekick tofind()
,findIndex()
loved tracking locations.
let monsters = ["goblin", "troll", "dragon"];
let dragonIndex = monsters.findIndex(monster => monster === "dragon");
console.log(dragonIndex);
// 2
"The dragon lurks at index 2!" he reported.
- some(): The Optimist
some()
was the type to always see a silver lining.
let spells = ["fireball", "ice", "healing"];
let hasHealing = spells.some(spell => spell === "healing");
console.log(hasHealing);
// true
"At least one of us can save the day!" cheered some.
- every(): The Perfectionist
every()
had high standards and accepted nothing less than perfection.
let grades = [95, 98, 100];
let allPassed = grades.every(grade => grade >= 90);
console.log(allPassed);
// true
"Everyone must excel!" demanded every.
- includes(): The Inspector
includes()
always checked for hidden threats.
let traps = ["pit", "spikes", "snakes"];
let hasSnakes = traps.includes("snakes");
console.log(hasSnakes);
// true
"Snakes? Why did it have to be snakes?" said includes nervously.
- sort(): The Organizer
When chaos reigned,sort()
brought order.
let heroes = ["Zelda", "Link", "Mario"];
let sortedHeroes = heroes.sort();
console.log(sortedHeroes);
// ["Link", "Mario", "Zelda"]
"Order restored!" declared sort proudly.