JavaScript30 - Day 7

By Camilla Krag Jensen naxoc |

Day 7 of #javascript30 is another array workout. I learn about some() and every() and feel good about it.

Arrays, chapter II

This time we are doing more filtering and searching in arrays. Some of the filtering uses Date — an old nemesis of mine. It's actually OK simple to use and I learned that with parentheses you can call functions on an object like this:

const year = ((new Date()).getFullYear();

rather than:

const date = new Date();
const year = date.getFullYear();

some()

some() will check if any item in the array passes some condition. It returns true if any item passes the condition.

every()

every() is a lot like some(), only this one returns true only id all items pass a condition.

splice()

splice() is a little tricky to understand because it can do many different things depending on what arguments you pass it. One thing that is super important to note, is that it mutates the array it is called on. MDN has a list of array functions that modify the array that is worth reading and understanding.

A couple of examples. Note that the array is modified!

const tapirTypes = ["Baird's", 'Malayan', 'Brazilian', 'Rabbit', 'Mountain'];
// Remove the animal that is not a tapir.
tapirTypes.splice(3, 1);
console.log(tapirTypes);
// [ "Baird's", "Malayan", "Brazilian", "Mountain" ]

// Add the newest discovered tapir to index 1.
tapirTypes.splice(1, 0, 'Kabomani');
console.log(tapirTypes);
// [ "Baird's", "Kabomani", "Malayan", "Brazilian", "Mountain" ]

find()

find() will search your array with the callback function you give it, and return the value of the first element that meets the callback function's test criteria. If nothing is found that satisfies the criteria, it returns undefined.

findIndex()

findIndex() is just like find(), but it returns the index of the item that satisfied the callback function test criteria. If nothing was found it returns -1.