Global Variables
const people = [
{ name: 'Wes', year: 1988 },
{ name: 'Kait', year: 1986 },
{ name: 'Irv', year: 1970 },
{ name: 'Lux', year: 2015 }
];
const comments = [
{ text: 'Love this!', id: 523423 },
{ text: 'Super good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen is my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 }
];
Exercises:
-
Figure out if at least one person is 19 or older using Array.prototype.some()?
const someAdults = people.some((person) => ((new Date()).getFullYear() - person.year) >= 19);
Output:
true
-
Find out if everyone is 19 or older using Array.prototype.every()?
const allAdults = people.every((person) => (((new Date()).getFullYear() - person.year) >= 19));
Output: (false at the time this was written 2019)
false
-
The find function, Array.prototype.find(), is like filter,
but instead returns just the one you are looking for. Find the comment with the ID of 823423 using this method.
const comment = comments.find((comment) => comment.id === 823423);
Output
-
Find the comment with this ID then delete the comment with the ID of 823423 using Array.prototype.findIndex().
const deleteComment = (ID) => {
const index = comments.findIndex(com => (com.id === ID));
if(index < 0) { // If not found, return
console.log(`ERROR: ${ID} could not be found.`)
return;
}
console.log(`Deleteing ${comments[index].id}........`);
// METHOD: 1
// comments.splice(index, 1) // Edits original array
// METHOD: 2
// Create new array and use slice
const newComments = [
...comments.slice(0, index),
...comments.slice(index + 1)
];
console.log('SUCCESS');
return newComments;
}
Normal Output:
// deleteComment(823423);
Output with error:
// deleteComment(823203);