Civilised Guide To Javascript Array Methods
Civilised Guide To Javascript Array Methods
array…
.find()
Something else
No
.flatMap()*
Sometimes more,
sometimes less
I want to…
JavaScript Array Methods
A string
Do something else R
I want to
A boolean At least one item passes a test .some()
check…
No No
https://jrsinclair.com
SA MP LE D ATA .find() .map()
This data is used across all the examples for each array method.
The .find() method will return The .map() method will apply a
const heroes = [ the first element in the array given function to every item in
{name: 'Hulk', strength: 90000}, that matches a test you provide. your array and give you a new
{name: 'Spider-Man', strength: 25000}, array with those values.
{name: 'Hawk Eye', strength: 136},
EXA MPLE:
{name: 'Thor', strength: 100000},
{name: 'Black Widow', strength: 136}, EXAMPLE:
function isHulk(hero) {
{name: 'Vision', strength: 5000}, return hero.name === 'Hulk'; function getName(hero) {
{name: 'Scarlet Witch', strength: 60}, } return hero.name;
{name: 'Mystique', strength: 120}, const hulk = heroes.find(isHulk); }
{name: 'Namora', strength: 75000},
const names = heroes.map(getName);
{name: 'Captain America', strength: 362},
{name: 'Deadpool', strength: 1814},
{name: 'Black Panther', strength: 1814},
];
The .filter() method takes The .concat() method adds This method is only a proposal, The .join() method will insert
your array and removes items new items to the end of your so it's not available everywhere. a given string between each item,
that don't pass a test you give it. array. You pass it a function that and return a joined-up string.
returns an array and it will
E XA M P L E : E X A MPLE: squish all the results together EXAMPLE:
The .every() method checks The .some() method checks that The .includes() method The .reduce() method is the
that every single item in your at least one item in your array checks that at least one item most flexible array iterator. It
array matches some criteria. matches some criteria. in your array matches some processes each item of the array
criteria. and lets you modify a value as
E XA M P L E : E X A MPLE: you go.
EXA MPLE:
function strong(hero) { function isHulk(hero) {
return hero.strength >= 200; return hero.name === 'Hulk'; EXAM PLE:
function getName(hero) {
} } return hero.name; function sumStrength(total, hero) {
const tuff = heroes.every(strong); const hulkIn = heroes.some(isHulk); return total + hero.strength;
}
const hulkIn = heroes }
.map(getName) const totalStength = heroes.reduce(
.includes('Hulk'); sumStrength,
0
);
.forEach()
E XA M P L E :
A Civilised Guide to
console.log(
'Name: ' + h.name
+ '\nStrength: ' + h.strength
);
}
heroes.forEach(logHero);
JavaScript Array Methods